R 通过根据索引列在其他列中拾取值来创建新的数据框列

R 通过根据索引列在其他列中拾取值来创建新的数据框列,r,dataframe,R,Dataframe,以下是数据帧“df”的(一小部分),其中包括: 11变量“v1”到“v11” 和索引列“indx”(带1),您可以这样做: f <- function(i){df[i,df[i,]$indx]} temp <- sapply(FUN=f,X=1:length(df[,1])) cbind(df,vsel=temp) f这是一个完全矢量化的解决方案,在速度方面很难击败 df$vsel <- as.matrix(df)[1:nrow(df) + nrow(df)*(df$indx

以下是数据帧“df”的(一小部分),其中包括:

11变量“v1”到“v11”

和索引列“indx”(带1),您可以这样做:

f <- function(i){df[i,df[i,]$indx]}
temp <- sapply(FUN=f,X=1:length(df[,1]))
cbind(df,vsel=temp)

f这是一个完全矢量化的解决方案,在速度方面很难击败

df$vsel <- as.matrix(df)[1:nrow(df) + nrow(df)*(df$indx-1)]

df$vsel拯救的矩阵索引!R有一种方法可以精确地完成您所描述的内容。
它简单而强大,但出人意料地鲜为人知

df$vsel <- df[cbind(1:nrow(df), df$indx)]

df$vsel这太棒了!你有关于这个命令的更多说明的链接吗?运行
?“[”
获取帮助页面。这确实是一个有用的提示,我不知道
[
可以做到这一点。所有3个答案都进行得很好!非常感谢大家。
f <- function(i){df[i,df[i,]$indx]}
temp <- sapply(FUN=f,X=1:length(df[,1]))
cbind(df,vsel=temp)
df$vsel <- as.matrix(df)[1:nrow(df) + nrow(df)*(df$indx-1)]
df$vsel <- df[cbind(1:nrow(df), df$indx)]