R:从具有x和y索引向量的矩阵或数据框中选择值向量

问题描述 投票:1回答:1

我正在尝试从矩阵,数据框,小标题或类似内容中进行选择。我可以编写一个函数来实现自己想要的功能,但是我想知道是否存在类似的内置函数。

我的功能如下:

matrixselect <- function(m, x, y, r=nrow(m)){ 
   if(! is.matrix(m)){m <- as.matrix(m)} 
   m[x + r * (y - 1)] 
   }  

并且例如,如果我想找到c(mydata[1,3], mydata[2,1], mydata[4,3])

mydata <- data.frame(LETTERS[1:4], LETTERS[5:8], LETTERS[9:12])
mydata
#   LETTERS.1.4. LETTERS.5.8. LETTERS.9.12.
# 1            A            E             I
# 2            B            F             J
# 3            C            G             K
# 4            D            H             L
mydata[c(1,2,4), c(3,1,3)]                     # gives more than I want:
#    LETTERS.9.12. LETTERS.1.4. LETTERS.9.12..1
# 1             I            A               I
# 2             J            B               J
# 4             L            D               L
matrixselect(mydata, c(1,2,4), c(3,1,3))       # gives what I want:
# [1] "I" "B" "L"
r select matrix
1个回答
1
投票

我们可以通过matrix ing将行/列索引用作cbind

mydata[cbind(c(1, 2, 4), c(3, 1, 3))]
#[1] "I" "B" "L"
© www.soinside.com 2019 - 2024. All rights reserved.