R: search for a column with a minimum value in each row when there is a related

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) which(x == min(x, na.rm = TRUE))) >k [[1]] [1] 3 [[2]] [1] 1 2 [[3]] [1] 3 [[4]] [1] 2 [[5]] [1] 2 3 

But I want the result to be as follows:

to
3 2 3 2 3

Thank you very much in advance.

+4
matrix r
source share
3 answers

Do you need 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 it.

+3
source share

You can use max.col(-dat, "last") , but first you need to set NA to Inf .

+3
source share

You can use this command to apply some functions to several (selected) columns of each row. Here I use this to create a new column for the maximum number of columns 1 and 2 (maxv12):

 d2<-transform(d, maxv12=apply(d[,c(1,2)],1, max, na.rm = TRUE)) 

My raw data (d):

 > 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 this command will give me the following:

 > 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 
+2
source share

All Articles