【问题标题】:R: How to get highest values colwise and their respective rownames?R:如何获得最高值 colwise 及其各自的行名?
【发布时间】:2016-08-16 00:18:55
【问题描述】:

我想获得我的 df 的所有列中的最高值(比如说最高 3)。对我来说重要的是获得这些值的行名。这是我的数据的一个子集:

structure(list(BLUE.fruits = c(12803543, 3745797, 19947613, 0, 130, 4), 
BLUE.nuts = c(21563867, 533665, 171984, 0, 0, 0),
BLUE.veggies = c(92690, 188940, 34910, 0, 0, 577),
GREEN.fruits = c(3389314, 15773576, 8942278, 0, 814, 87538),
GREEN.nuts = c(6399474, 1640804, 464688, 0, 0, 0), 
GREEN.veggies = c(15508, 174504, 149581, 0, 0, 6190),
GREY.fruits = c(293869, 0, 188368, 0, 8, 0),
GREY.nuts = c(852646, 144024, 26592, 0, 0, 0), 
GREY.veggies = c(2992, 41267, 6172, 0, 0, 0)),
.Names = c("BLUE.fruits", "BLUE.nuts", "BLUE.veggies", 
"GREEN.fruits", "GREEN.nuts", "GREEN.veggies", "GREY.fruits", 
"GREY.nuts", "GREY.veggies"), row.names = c("Afghanistan", "Albania", 
"Algeria", "American Samoa", "Angola", "Antigua and Barbuda"),
class = "data.frame")

到目前为止,我在第一列中尝试过这个:

as.data.frame(x[,1][order(x[,1], decreasing=TRUE)][1:10]

但是,我没有得到原始的行名,我需要像 apply/lapply 这样的方法来遍历所有列(~ 150 列)。想法?谢谢

【问题讨论】:

标签: r max apply lapply


【解决方案1】:

这可能会有所帮助: Print one column of data frame with row names

因此,如果您稍微调整一下代码,您会得到: (一个长长的丑陋代码行 =),它返回一个列表,你想要的输出格式是什么 - 基于你的“lapply”标签?)

lapply(1:dim(df)[2], function(col.number) df[order(df[, col.number], decreasing=TRUE)[1:3], col.number, drop = FALSE])

【讨论】:

    【解决方案2】:

    你可以写一个列最大值函数colMax

    colMax <- function(data) sapply(data, max, na.rm = TRUE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多