R: finding column with minimum value in each row when there is a tied

后端 未结 3 1332
误落风尘
误落风尘 2021-01-19 21:51

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         


        
3条回答
  •  悲哀的现实
    2021-01-19 22:01

    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
    

提交回复
热议问题