r - 在数据框中选择带有索引的列和行值

标签 r

这个问题在这里已经有了答案:





How to subset a matrix with different column positions for each row? [duplicate]

(2 个回答)


5年前关闭。




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

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 ,但我不知道该怎么做……或者是否还有其他方法可以做到这一点。

最佳答案

由于您的索引位于 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 

关于r - 在数据框中选择带有索引的列和行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33996891/

相关文章:

R 机器学习模型部署为 Web 服务

r - 使用给定两个向量的条件在 R 图上绘制曲线

r - 从列表列表到长格式的 tibble

r - 如何将值矩阵转换为二进制矩阵

r - %in% vs '==' 比较日期和 date_as_string

r - ggiraph图未出现在 Shiny 的应用程序中,但可在RStudio中使用

r - 根据敏感性和特异性确定阈值

r - igraph 与 sna : can one do something well the other can't or does poorly?

r - 用 R 分析时间序列

R:几何平均值的快速计算