Anand Anand - 29 days ago 12
R Question

Getting column names of each row in order

I have a dataframe with three columns of numeric values. I want to sort each row and print a string with the column names in sorted order for each row. Here is my code:

> df <- data.frame(x = c(1,2,3), y = c(3,1,2), d = c(4,0, 5))
> df
x y d
1 1 3 4
2 2 1 0
3 3 2 5
> for(r in 1:nrow(df))
+ print(paste(colnames(sort(df[r,])), collapse = " "))
[1] "x y d"
[1] "d y x"
[1] "y x d"


This does work, but it takes a long time when I have a large dataframe. Is there a more effective way to perform the sort? I tried to use apply, but that just gave back blank strings:

> apply(df, 1, function(row) paste( colnames( sort( row, decreasing = T )) , collapse = " " ))
[1] "" "" ""


When I call the function within apply on a single row, it works:

> paste( colnames( sort( df[1,], decreasing = T )) , sep = " " )
[1] "d" "y" "x"


I am mainly looking for a faster way to perform this operation on each row of a large dataframe than the for loop. And I think apply could be faster, but cannot get it to work.

Answer
t(apply(df, 1, function(x) names(x)[order(x)]))