我正试图创建一个循环,根据数据帧外部的预测向量对数据帧(响应(的每一行执行lm。预测器的值和长度因行所属的类别(df$Group(而异。如果您能帮助我创建一个循环,为每一行执行lm,并将系数保存到单个向量/数据帧中,我将不胜感激。此外,要在具有相同结构的多个数据帧中运行循环,然后将系数保存到单个数据帧中,我应该对代码进行哪些更改?下面是我尝试过的——它不保存系数。
dfList <- list(df,df1,df2)
df <- data.frame(ID=c(1:10),Group=c("A","A","A","A","B","B","B","B","B","B"), T1= rnorm(10, mean=1, sd=1),
T2= rnorm(10, mean=2, sd=1),T3= seq(40,58,by=2),T4= seq(10,28,by=2))
A <- df$ID
B <- df$Group
C <- numeric(length=length(A))
x1 <- c(1:4)
x2 <- c(2:4)
for (i in length(A)){
if(B[i] == "A"){C[i] <- apply(df[,c(3:6)],1,function(y) lm(y~x1)$coefficients[2])[i]}
if(B[i] == "B"){C[i] <- apply(df[,c(4:6)],1,function(y)lm(y~x2)$coefficients[2])[i]}
}
感谢您的帮助!非常感谢。
你想做这样的事情吗?
list_df <- split(df, df$Group)
A_coeff <- apply(list_df[[1]][, 3:6], 1, function(y) lm(y~x1)$coefficients[2])
B_coeff <- apply(list_df[[2]][, 4:6], 1, function(y) lm(y~x2)$coefficients[2])