Here is my data example:
>dat <- matrix(c(59,50,48,44,44,NA,78,59,42,67,51,NA,72,64,64),byrow=TRUE,ncol=3)
>k <- apply(dat, 1, function(x) whic
You can use max.col(-dat, "last")
, but you'll have to set NA
s to Inf
first.
do you want a maximum index for each row?
then,
> k <- apply(dat, 1, function(x) max(which(x == min(x, na.rm = TRUE))))
> k
[1] 3 2 3 2 3
will do that.
You can use this command to apply some functions on multiple (selected) columns of each row. Here I am using this to create a new column for max of columns 1 and 2 (maxv12):
d2<-transform(d, maxv12=apply(d[,c(1,2)],1, max, na.rm = TRUE))
My original data (d) is:
> head(d)
V1 V2 V3 V4
1 2.0960 3.5364 2.2627 3.4358
2 1.7210 3.3172 1.6559 3.3083
3 1.7950 3.2874 2.2214 3.8520
4 2.0187 3.4038 1.9036 3.4158
5 1.8991 3.6274 1.8083 3.4552
6 1.7382 3.1765 2.6270 4.0960
And applying that command would give me this:
> head(d2)
V1 V2 V3 V4 maxv12
1 2.0960 3.5364 2.2627 3.4358 3.5364
2 1.7210 3.3172 1.6559 3.3083 3.3172
3 1.7950 3.2874 2.2214 3.8520 3.2874
4 2.0187 3.4038 1.9036 3.4158 3.4038
5 1.8991 3.6274 1.8083 3.4552 3.6274
6 1.7382 3.1765 2.6270 4.0960 3.1765