在for循环中一次调用三列变量

时间:2017-09-15 15:24:12

标签: r loops

我有以下带有Y列的示例数据集(可以忽略)和两个变量X1和X2,它们被编码为三列中的虚拟变量

Y0 <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
X1.0 <- c(1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0)
X1.1 <- c(0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1)
X1.2 <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
X2.0 <- c(1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0)
X2.1 <- c(0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1)
X2.2 <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)

df <- data.frame(Y,X1.0,X1.1,X1.2,X2.0,X2.1,X2.2)

我正在尝试将函数应用于每个变量。所以在应用该函数之前,我尝试了以下for循环来调用每个变量(我希望在第二个循环中调用第2列:4后跟5:7)

for (i in 1:2)
{
onevar <- df[,3i-1:3i+1]
##to insert/apply a function here and store the value for each variable 
}

但是我收到了此错误消息

Error in .subset(x, j) : invalid subscript type 'complex'
In addition: Warning message:
In `[.data.frame`(a0, , 0+3i - 1:(0+3i) + 1) :
imaginary parts discarded in coercion

我非常感谢任何想法或建议,因为我需要将其应用于具有许多变量的更大数据集。

1 个答案:

答案 0 :(得分:2)

您可以按照df认为您所指的complex numbers的方式在循环中对R进行索引。如果您希望R多个两个术语,则必须明确乘以*

如果您想要2:4,然后5:7,则可以使用

for (i in 1:2){
    inds <- (3*i-1) : (3*i+1) 
    # do your function here
}

或者在我看来更好一点:

for(i in 0:1){
  inds <- (2:4) + 3*i
}