首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在数据帧中选择具有索引的列和行值。

在数据帧中选择具有索引的列和行值。
EN

Stack Overflow用户
提问于 2015-11-30 10:51:58
回答 2查看 1.1K关注 0票数 4

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

代码语言:javascript
复制
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"))) 

然后,我取最大值的指数:

代码语言:javascript
复制
ind <- apply(abs(mat), 2, which.max) 

这给了我:

代码语言:javascript
复制
LO3  Tx  Gh  RH  SR 
2   5   4   5   4

我现在想要的是,它得到了每一列的这些职位的价值。这将是:

代码语言:javascript
复制
LO3       Tx        Gh
0.4282915 0.4863608  -0.4962140 .....

我试着使用apply,但如果有其他方法,我不知道如何使用it..or。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-30 11:04:47

由于在ind中有索引,一种方法是使用mapply

代码语言:javascript
复制
#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 
票数 3
EN

Stack Overflow用户

发布于 2015-11-30 11:05:58

这能为你做到:

代码语言:javascript
复制
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结果的名称

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33996891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档