我會通過初始化數據集並添加行來解決這個問題。這避免了使用rbind。我的方法在編制索引時容易出錯,所以我將第二個循環的索引變量更改爲與第一個循環中的索引變量不同的變量。
#first i create sample df with 3 random variables and index
df=data.frame("var1"=runif(18,min=0,max=1),
"var2"=runif(18,min=0,max=1),
"var3"=runif(18,min=0,max=1),
"index2"=c(rep(c("A","B","C"),6)),
"index1"=c(rep(1,9),rep(2,9)))
#lists for subseting data in loops
list.1=list(1,2)
list.2=list("A","B","C")
#here I initialize the dataset
MyCalcs.tot <- as.data.frame(matrix(rep(NA, length(list.1)*length(list.2)*4), ncol = 4))
names(MyCalcs.tot) <- c("INDEX1","CALC1", "CALC2", "CALC3")
#first loop based on list.2
for (i in 1:length(list.2)){
i2=list.2[i]#indicator for inside loop to subset based on letter
#your second loop used the same index as the first,
#this migth lead to confusion, thus i changed it to a j
for (j in 1:length(list.1)){
x=subset(df,df$index1 %in% list.1[j] & df$index2 %in% i2)#subseting data
x=subset(x,select=c("var1","var2"))#second subset is not needed for example but it exists in my loop
MyCalcs=data.frame(
"INDEX1"=list.1[j],
"CALC1"=mean(x$var1+x$var2),
"CALC2"=mean(x$var1-x$var2),
"CALC3"=mean(x$var1*x$var2)
)#here I make some simple calculation
MyCalcs.tot[(i - 1)*length(list.1) + j,] <- MyCalcs #adding your calculations to the next row.
print(MyCalcs)#this i want put into data.frame
}}
MyCalcs.tot是所需的數據幀
你也可以完全避免使用循環和使用應用功能:
#first i create sample df with 3 random variables and index
df=data.frame("var1"=runif(48,min=0,max=1),
"var2"=runif(48,min=0,max=1),
"var3"=runif(48,min=0,max=1),
"index3"=c(rep(c("do","re","mi","fa"),12)),
"index2"=c(rep(c("A","B","C"),16)),
"index1"=c(rep(1,24),rep(2,24)))
comb <- as.data.frame(cbind(unlist(lapply(list.1,function(x)rep(x,length(list.2)*length(list.3)))),
rep(unlist(lapply(list.2,function(x)rep(x,length(list.3)))),length(list.1)),
rep(unlist(list.3),length(list.1)*length(list.2))))
names(comb) <- c("INDEX1","INDEX2","INDEX3")
comb$CALC1 <- apply(comb,1,function(x)mean(apply(df[,1:2],1,function(y)y[1]+ y[2])[which(df$index1 == x[1] & df$index2 == x[2] & df$index3 == x[3])]))
comb$CALC2 <- apply(comb,1,function(x)mean(apply(df[,1:2],1,function(y)y[1]- y[2])[which(df$index1 == x[1] & df$index2 == x[2] & df$index3 == x[3])]))
comb$CALC3 <- apply(comb,1,function(x)mean(apply(df[,1:2],1,function(y)y[1]* y[2])[which(df$index1 == x[1] & df$index2 == x[2] & df$index3 == x[3])]))
可以顯示基於對數據樣本所需的輸出? –