anus anus - 3 months ago 5
R Question

find column names corresponding to least value of each row in R

i have to extract column names corresponding to least 10 values for each row of a data frame and print it in new data frame.Can anyone help me do that?

my data frame looks like this:(15 x 15 matrix)

> head(yt)
V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15
1 0 966 1513 2964 1149 927 1611 1510 390 466 1820 1718 504 1179
2 966 0 2410 1520 1817 729 686 290 1823 168 2027 172 1610 1500
3 1513 2410 0 604 481 2742 1833 826 214 1618 1712 567 544 1313
4 2964 1520 604 0 595 1289 1446 466 1139 430 428 201 452 1574
5 1149 1817 481 595 0 494 550 2641 765 934 1813 1516 378 1363
6 927 729 2742 1289 494 0 1279 1197 2956 299 888 491 1408 1432


for each of the 15 rows i would like to know column names for least 10 columns

i know which.min gives least column name for each row but can you let me know other ways of computing least 10 values

Answer

The order function will give the ordering of a vector. So the first value of its result corresponds to the index of the smallest value in the vector. The second to the index of the second smallest etc. Using it in a function and using the apply function we can apply it to all rows. The apply function's result is column wise, which you probably don't want, so the transpose is taken over the result.

first_10 <- function(x) order(x)[1:10]
t(apply(dat, 1, first_10))
Comments