Stewart Wiseman Stewart Wiseman - 12 days ago 5
R Question

Apply function on rows to extract col names (not values) in r

I have the following

mat <- structure(c(56L, 45L, 64L, 43L, 67L, 17L, 164L, 158L, 150L,177L,111L, 11L, 10L, 9L, 10L), .Dim = c(5L, 3L), .Dimnames = list(c("Bob", "Sam", "Bill", "Mary", "Ted"), c("X1", "X2", "X3"
)))


I used this to sort by row:

apply(mat, 1, sort)


However, instead of getting the VALUES, I would like the column names. Is this possible? The output would need to look this this:

mat.res <- structure(c("X2", "X1", "X3", "X3", "X1", "X2", "X3", "X1", "X2", "X3", "X1", "X2", "X3", "X1", "X2"), .Dim = c(3L, 5L), .Dimnames = list(
NULL, c("Bob", "Sam", "Bill", "Mary", "Ted")))

Answer

Is this what you are looking for ?

apply(mat,1,function(x){names(sort(x))})
Comments