【问题标题】:Select column and row values with an index in data frame [duplicate]在数据框中选择具有索引的列和行值[重复]
【发布时间】:2015-11-30 10:51:58
【问题描述】:

我有一个相关矩阵,我试图保持每对(行/列)的最大值(考虑绝对值)。我想问,如果我有特定最大值的位置索引,如何提取值。价值。 这是我的示例:

mat <- structure(c(0, 0.428291512801413, 0.124436112431533,    -0.345870125921382, 
             0.391613957773281, 0.428291512801413, 0, 0.341415068127906, -0.346724601510298, 
             0.486360835614514, 0.124436112431533, 0.341415068127906, 0, -0.496213980990412, 
             0.41819049956841, -0.345870125921382, -0.346724601510298, -0.496213980990412, 
             0, -0.80231408836218, 0.391613957773281, 0.486360835614514, 0.41819049956841, 
            -0.80231408836218, 0), .Dim = c(5L, 5L), .Dimnames = list(c("LO3","Tx", "Gh", "RH", "SR"), c("LO3", "Tx", "Gh", "RH", "SR"))) 

然后,我取最大值的索引:

ind <- apply(abs(mat), 2, which.max) 

这给了我:

LO3  Tx  Gh  RH  SR 
2   5   4   5   4

我现在想要的是,它为每一列获取这些位置的值.. 这将是:

LO3       Tx        Gh
0.4282915 0.4863608  -0.4962140 .....

我尝试使用apply,但我不知道该怎么做..或者是否有其他方法可以做到这一点。

【问题讨论】:

  • mat[cbind(1:nrow(mat), ind)]

标签: r


【解决方案1】:

由于您的索引位于 ind 中,一种方法是使用 mapply

#the first argument is the function call 
#second argument is your matrix coerced to data.frame
#third argument is your indices
#each time an index will be used in conjunction to a column
#and you get your result
mapply(function(x,y) x[y], as.data.frame(mat), ind)
#       LO3         Tx         Gh         RH         SR 
# 0.4282915  0.4863608 -0.4962140 -0.8023141 -0.8023141 

【讨论】:

  • 非常感谢,完美!
  • 不客气@user3231352。很高兴我能帮上忙:)
【解决方案2】:

这可以为你做到:

mapply(function(i,j) sample[i,j], seq_len(ncol(sample)), ind)

> mapply(function(i,j) sample[i,j], seq_len(ncol(sample)), ind)
[1]  0.4282915  0.4863608 -0.4962140 -0.8023141 -0.8023141

如果你愿意,你可以设置来自ind的结果名称

【讨论】:

    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 2012-08-10
    • 2015-10-04
    • 2021-03-22
    • 2013-02-05
    相关资源
    最近更新 更多