我以資料集mtcars為例。目標是:
- 第 1 步:使用回圈運行結果變化的回歸,而每個模型的自變數保持不變。
- 第 2 步:在第 1 步中轉換每個模型的殘差
我的代碼:
library(tidyverse)
data("mtcars")
# Plan:
# Step 1: Outcome = cyl disp hp drat
# Step 2: Transform residual from step 1
# The outcomes are all the other coloumns
outcome = colnames(mtcars[, -c(2:5)])
for (i in outcome){
# Step 1: Run the model using a loop with changing outcome
formula = as.formula(paste0(i, "~ cyl disp hp drat"))
model = lm(formula, data = mtcars, na.action = na.exclude)
# Save the residuals from each model as new columns with the suffix '.res'
mtcars[, paste0(i, ".res")] = residuals(model)
# Step 2: Transform the residuals and save them as new columns with the suffix '.invn'
mtcars[, paste0(i, ".invn")] =
qnorm((rank(mtcars[,get(paste0(i,".res"))],na.last="keep")-0.5)/sum(!is.na(mtcars[,get(paste0(i,".res"))])))
}
但是,我收到一個錯誤Error in get(paste0(i, ".res")) : object 'mpg.res' not found,這是從第 2 步開始的。
- 我認為的原因是因為在使用 索引資料集中的列時
[],必須將列名放在引號中。所以,如果我說的話,mtcars[, 'mpg.res']我就不會收到這個錯誤。 - 盡管如此,問題是列名會根據不同而改變,
i所以我不能加paste0(i, ".res")引號。 - 總之,我的問題是:當列名是回圈的一部分時,如何索引新創建的列?我試過
eval(parse())了,但沒有用。
PS:我知道我可以使用purrr::maporapply讓我的生活更輕松,但我真的很想學習如何在使用回圈時解決這個問題。
uj5u.com熱心網友回復:
另一種簡單的方法可能是始終使用最后一個列名,因為您總是將該列附加到data.frame.
mtcars[, colnames(mtcars)[length(colnames(mtcars))]]
將您的代碼翻譯成:
mtcars[, paste0(i, ".invn")] =
qnorm((rank(mtcars[, colnames(mtcars)[length(colnames(mtcars))]],na.last="keep")-0.5)/sum(!is.na(mtcars[, colnames(mtcars)[length(colnames(mtcars))]])))
uj5u.com熱心網友回復:
只需洗掉get()
# Step 2: Transform the residuals and save them as new columns with the suffix '.invn'
mtcars[, paste0(i, ".invn")] =
qnorm((rank(mtcars[,paste0(i,".res")],na.last="keep")-0.5)/sum(!is.na(mtcars[,paste0(i,".res")])))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/498166.html
上一篇:如何去除每個樣本的前綴
下一篇:在R中的火山圖中格式化p值截止線
