在行上应用函数以在r中提取列名(而不是值)

时间:2016-11-24 15:51:33

标签: r

我有以下

 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"
)))

我用它按行排序:

 apply(mat, 1, sort)

然而,我不想获得VALUES,而是想要列名。这可能吗?输出需要看这个:

 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")))

1 个答案:

答案 0 :(得分:2)

这是你在找什么?

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