我已经从数据帧数据中创建了向量并将它们存储在列表中。举个例子:
# Simulation data
vec2 <- c(2:20)
vec3 <- c(21:39)
vec4 <- c(31:49)
vec5 <- c(2:20)
vec6 <- c(2:20)
vec7 <- c(21:39)
vec8 <- c(31:49)
vec9 <- c(21:39)
vec10 <- c(31:49)
# Make simulated df to replicate something close to what I have
df <- data.frame(vec2,vec3,vec4,vec5,vec6,vec7,vec8,vec9,vec10)
所以我们有一个虚拟df。接下来,我将提取回归所需的行(y):
# Extract data from df and place in a list
var <- list()
for (i in 1:nrow(df)) {
var[i] <- list(c(df$vec2[i],
df$vec3[i],
df$vec4[i],
df$vec5[i],
df$vec6[i],
df$vec7[i],
df$vec8[i],
df$vec9[i],
df$vec10[i]))
}
# Create x regression variable input
log.lags <- c(2:10)
好的,现在我们应该有一个列表,就是这么长:
长度(VAR) [1] 19
y和x回归变量的长度相同:
> length(var[[1]])
[1] 9
> length(log.lags)
[1] 9
现在我想在var列表上运行回归作为y自变量,并将log.logs作为x运行,独立。
I try this with the following:
#Initialize list
results<-vector("list", length(var))
# Run regression
for(i in 1:length(df)){
results[[i]]<-lm(log(var[[i]])~log(log.lags), data = var)
}
这有效...我怎样才能从结果列表中提取系数?
好的想通了:
results<-vector("list", length(var))
coef<-vector("list", length(var))
for(i in 1:length(df)){
results[[i]]<-lm(log(var[[i]])~log(log.lags), data = var)
coef[[i]]<- coef(results[[i]])[2]
}
答案 0 :(得分:2)
这个怎么样?
res <- lapply(var, function(x) lm(log(x)~log(log.lags)))
coefs <- lapply(res, function(x) coef(x)[2])