2017-09-15 57 views
0

我已其中Y列下面的例子中的數據集(可以忽略)時間和兩個變量X1和X2它們在三列每呼叫變量三列在for循環

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調用:接着用5 4: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

非常感謝@ d.b能正常工作。 – Shima

回答

2

您以R認爲您指的是complex numbers的方式在循環內索引df。如果你想要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 
} 
+0

太棒了!謝謝@肯S.這工作正常。 – Shima