[英]How to append dataframe column names with for-loop iteration count in R?
[英]How do i add column names to my for-loop in R
我做了一個循環來運行回歸 model 的所有可能組合。因為我只需要保留 model 的殘差,所以我這樣做了:
df <- data.frame(t(combn(colnames(orig_df), m = 2)))
test = NULL
for (i in 1:(nrow(df)-1)) {
for (j in (i+1):nrow(df)) {
x <- lm(orig_df[[i]] ~ orig_df[[j]], data = orig_df)
y <- x$residuals
test <- cbind(test, y)
}
}
但是,我的問題是將名稱添加到新數據框(此處命名為“test”)。 我認為區分殘差的一個好方法是添加x$call[2]
。 但是,如果我創建循環以便:
test = NULL
for (i in 1:(nrow(df)-1)) {
for (j in (i+1):nrow(df)) {
x <- lm(orig_df[[i]] ~ orig_df[[j]], data = Telekom)
y <- x$residuals
test <- cbind(test, y)
colnames(test) <- paste(x$call[2])
}
}
在此之后,循環停止正常工作,顯示的錯誤是: length of 'dimnames' [2] not equal to array extent
。 我的錯誤是什么?
提前致謝!
對於第一個循環:
對於第二個循環:
可以使用mtcars
數據重現該問題
> model <- lm(mtcars[[1]] ~ mtcars[[2]])
> model$call
lm(formula = mtcars[[1]] ~ mtcars[[2]])
我們可能會在之后分配call
> model$call[[2]] <- as.formula(paste0(names(mtcars)[1], "~ ", names(mtcars)[2]))
> model$call
lm(formula = mpg ~ cyl)
在 OP 的循環中,這個修改可能有效
test = NULL
for (i in 1:(nrow(df)-1)) {
for (j in (i+1):nrow(df)) {
x <- lm(orig_df[[i]] ~ orig_df[[j]], data = Telekom)
x$call[[2]] <- as.formula(paste0(names(orig_df)[i], "~ ", names(orig_df)[j])))
y <- x$residuals
test <- cbind(test, y)
colnames(test)[ncol(test)] <- paste(x$call[[2]])
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.