【发布时间】:2021-03-27 00:11:04
【问题描述】:
对于可重现的示例:
test <- structure(list(IDcount = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2), year = c(1,
2, 3, 4, 5, 1, 2, 3, 4, 5), Otminus1 = c(-0.28, -0.28, -0.44,
-0.27, 0.23, -0.03, -0.06, -0.04, 0, 0.02), N.1 = c(NA, -0.1,
0.01, 0.1, -0.04, -0.04, -0.04, -0.04, -0.05, -0.05), N.2 = c(NA,
NA, -0.09, 0.11, 0.06, NA, -0.08, -0.08, -0.09, -0.09), N.3 = c(NA,
NA, NA, 0.01, 0.07, NA, NA, -0.12, -0.13, -0.13), N.4 = c(NA,
NA, NA, NA, -0.04, NA, NA, NA, -0.05, -0.05), N.5 = c(NA, NA,
NA, NA, NA, NA, NA, NA, NA, -0.13)), row.names = c(NA, -10L), groups = structure(list(
IDcount = c(1, 2), .rows = structure(list(1:5, 6:10), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
results <- structure(list(IDcount = c(1, 2), N.1 = c(NA, NA), N.2 = c(NA,
NA), N.3 = c(NA, NA), N.4 = c(NA, NA), N.5 = c(NA, NA)), row.names = c(NA,
-2L), class = "data.frame")
我正在执行lm 回归,没有拦截嵌套 for 循环中的 data frame“测试”,并使用此代码将系数写入“结果”:
index <- colnames(test) %>% str_which("N.")
betas <- matrix(nrow=length(unique(test$IDcount)), ncol=2)
colnames(betas) <- c("Intercept", "beta")
for (j in colnames(test)[index]) {
for (i in 1:2) {
tmp <- test[test$IDcount==i, c("Otminus1", j)]
if(any(colSums(!is.na(tmp)) == 0)) next
betas[i,] <- coef(lm(Otminus1 ~ . -1, tmp))
}
betas <- data.frame(betas)
results[[j]] <- betas$beta
}
这非常有效。但我现在想切换 y 和 x 变量,以便循环中的公式读取:
betas[i,] <- coef(lm(. ~ Otminus1 -1, tmp))
但是这样做时我收到以下错误消息:
Error in model.frame.default(formula = . ~ Otminus1 - 1, data = tmp, drop.unused.levels = TRUE) :
Object is not a matrix
我试图通过介绍as.matrix来考虑这一点:
betas[i,] <- coef(lm(. ~ Otminus1 -1, as.matrix(tmp)))
但是当我这样做时,我收到了这个错误:
Error in model.frame.default(formula = . ~ Otminus1 - 1, data = as.matrix(tmp), :
'data' must be a data frame not matrix or an array
我找到了Error in model.frame.default(object, data, xlev = xlev) : object is not a matrix,但我无法将其应用到我的示例中。
【问题讨论】: