R 使用向量中的行-列索引从数据帧中提取值
使用列位置索引的向量,例如:R 使用向量中的行-列索引从数据帧中提取值,r,R,使用列位置索引的向量,例如: > i <- c(3,1,2) 只需使用矩阵索引,如下所示: dframe[cbind(seq_along(i), i)] # [1] "g" "b" "f" cbind(seq_沿(i),i)部分创建了一个包含要提取的相关行和列的两列矩阵。这样如何: Df <- data.frame( x=c("a","b","c"), y=c("d","e","f"), z=c("g","h","i")) ## i <- c(3,1,
> i <- c(3,1,2)
只需使用矩阵索引,如下所示:
dframe[cbind(seq_along(i), i)]
# [1] "g" "b" "f"
cbind(seq_沿(i),i)
部分创建了一个包含要提取的相关行和列的两列矩阵。这样如何:
Df <- data.frame(
x=c("a","b","c"),
y=c("d","e","f"),
z=c("g","h","i"))
##
i <- c(3,1,2)
##
index2D <- function(v = i, DF = Df){
sapply(1:length(v), function(X){
DF[X,v[X]]
})
}
##
> index2D()
[1] "g" "b" "f"
Df
dframe[cbind(seq_along(i), i)]
# [1] "g" "b" "f"
Df <- data.frame(
x=c("a","b","c"),
y=c("d","e","f"),
z=c("g","h","i"))
##
i <- c(3,1,2)
##
index2D <- function(v = i, DF = Df){
sapply(1:length(v), function(X){
DF[X,v[X]]
})
}
##
> index2D()
[1] "g" "b" "f"