[英]Learning R: How do I output the element of certain y vector elements with indices that correspond to certain x vectors?
[英]R: Selecting a vector of values from a matrix or dataframe with vectors of x and y indices
我正在嘗試從矩陣或數據框或小標題或類似內容中進行選擇。 我可以編寫一個函數來做我想做的事,但我想知道是否有類似的內置功能。
我的功能看起來像:
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"
我們可以通過cbind
將行/列索引用作matrix
mydata[cbind(c(1, 2, 4), c(3, 1, 3))]
#[1] "I" "B" "L"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.