 Anand -4 years ago 105
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 = " "))
 "x y d"
 "d y x"
 "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 = " " ))
 "" "" ""
``````

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

``````> paste( colnames( sort( df[1,], decreasing = T )) , sep = " " )
 "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. joel.wilson
``````t(apply(df, 1, function(x) names(x)[order(x)]))