简体   繁体   English

R:为前 n 列值制作带有行名的表格

[英]R: Make table with rownames for top n column values

I have a data frame with numeric count values.我有一个带有数字计数值的数据框。 I would like to create a new table that has the rownames of the top n values for each column.我想创建一个新表,其中包含每列前 n 个值的行名。

df <- data.frame(a = c(1,4,5,2), b = c(7,1,4,6), c = c(5,6,7,1)
rownames(df) <- c(w,x,y,z)

using n = 2 my desired output would be使用 n = 2 我想要的输出是

a一种 b c C
y w y
x X z z z z

I am able to extract the top 5 values for each column using the following df2 <- apply(df, 2, function(x) sort(unique(x),decreasing =TRUE)[1:5]) but I cannot figure out how to get the rownames that correspond to each value.我能够使用以下df2 <- apply(df, 2, function(x) sort(unique(x),decreasing =TRUE)[1:5])提取每列的前 5 个值,但我无法弄清楚如何获取与每个值对应的行名。

A possible solution:一个可能的解决方案:

df <- data.frame(a = c(1,4,5,2), b = c(7,1,4,6), c = c(5,6,7,1))
rownames(df) <- c("w","x","y","z")

f <- function(x) names(sort(x,decreasing = T))[1:2]

apply(df,2,f)

#>      a   b   c  
#> [1,] "y" "w" "y"
#> [2,] "x" "z" "x"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM