我正在完成一项我想要自动化的任务,我不熟悉循环和变量分配,所以任何帮助都会很棒。
该任务有两个步骤:首先使用一个不同的字符彼此获取少量数据集,然后应用一个lm模型,该模型的变量也具有与数据集名称一致的一个不同字符。例如:使用数据集与名称SF_FinalviewQ3_2013_Day**3**_BaseLine
并应用包含IsDepositorDay**3**
和IsDueDay**3**
等变量的lm。我有大约10个数据集和50个变量,我想自动化,所以我尝试使用此代码基于此网站的answare但我收到错误。
Error: unexpected symbol in:
" eval(parse(text = paste0("SF_FinalviewQ3_2013_Day", i, "_BaseLine<-maindata"))
f"
# Here is my code
f <- NA # first I reset f
index <- 1 # this will be the index
for(i in c(3,10){ #3,10 are the only charcter that changes in the data sets and in vars names.
var[i]<-paste("IsDepositorDay",i,sep="")
eval(parse(text = "var[i]"))
maindata<-paste("SF_FinalviewQ3_2013_Day",i,"_BaseLine",sep="")
eval(parse(text = paste0("SF_FinalviewQ3_2013_Day", i, "_BaseLine<-maindata"))
f[index]<-lm(IsDepositorDay180~ var1,data=maindata)
index <- index + 1
}
我该如何解决?
#per a request to make my example reproducible i did the following changes:
dat1 <- read.table(text = " target birds_1 wolfs_1 snakes_1
0 3 9 7
1 3 8 4
1 1 2 8 ",header = TRUE)
dat2 <- read.table(text = " target birds_2 wolfs_2 snakes_2
1 3 2 4
0 8 8 3
5 1 2 8 ",header = TRUE)
f <- NA # first I reset f
index <- 1 # this will be the index
for(i in c(1,2)){ #1,2 are the only charcter that changes in the data sets and in vars names.
birds_[i]<-paste("birds_",i,sep="")
wolfs_[i]<-paste("wolfs_",i,sep="")
snakes_[i]<-paste("snakes_",i,sep="")
eval(parse(text = "birds_[i]"))
eval(parse(text = "wolfs_[i]"))
eval(parse(text = "snakes_[i]"))
maindata<-paste("dat",i,sep="")
eval(parse(text = paste0("dat", i, "<-maindata"))
f[index]<-lm(target~ birds_[i]+snakes_[i],data=maindata)
index <- index + 1
}
答案 0 :(得分:2)
如果我理解正确,可以将lm对象保存在列表中,如下所示。删除未包含在公式中的列以使其简单。
# way 1 with loop
f <- list()
dat <- list(dat1, dat2)
for(i in 1:2) f[[i]] <- lm(target ~ ., data = dat[[i]][,-3])
# way 2 with lapply
dat <- list(dat1[,-3], dat2[,-3])
lapply(dat, lm, formula = target ~ .)
[[1]]
Call:
FUN(formula = ..1, data = X[[1L]])
Coefficients:
(Intercept) birds_1 snakes_1
4.3333 -0.6667 -0.3333
[[2]]
Call:
FUN(formula = ..1, data = X[[2L]])
Coefficients:
(Intercept) birds_2 snakes_2
-3 0 1
您设置的一些建议是
然后公式可以很容易设置,关键变量(系数......)也很容易提取。