Select the minimum column in a specific row (R)

前端 未结 1 1533
春和景丽
春和景丽 2021-01-23 22:12

I have some issue with R. I try to extract the column with the minimum value in each row. Let me explain :

Test = data.frame(Day1 = c(1,6,3,8), Day2 = c(2,5,4,9)         


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 22:28

    You can use apply the following to find the minimum value in each row.

    Test$minimum <- apply(Test,1,which.min)
    

    Setting a parameter of 1 runs the code which.min over each row of Test.

    To get the column name of the minmum column, add colnames(Test) before apply

    Test$minimum_day <- colnames(Test)[apply(Test,1,which.min)]
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题