[英]Converting a character into a variable name
我需要使用 model.matrix 函數將數據框轉換為矩陣。 原始數據框的名稱是 train,感興趣的結果變量稱為 adequacy_ratio_total_percent。 下面的 R 代碼有效。
X_train_matrix <- model.matrix(adequacy_ratio_total_percent ~ ., train)[, -1]
但是,由於我的結果變量可能會有所不同,我希望使用下面的代碼來簡化結果變量的更改,但這不起作用。
list_outcome <- c("adequacy_ratio_total_percent")
X_train_matrix <- model.matrix(list_outcome ~ ., train)[, -1]
model.frame.default(object, data, xlev = xlev) 中的錯誤:可變長度不同(為 'adequacy_ratio_total_percent' 找到)
我還嘗試了以下方法,但也不起作用。
list_outcome <- c("adequacy_ratio_total_percent")
X_train_matrix <- model.matrix(train$list_outcome ~ ., train)[, -1]
model.frame.default(對象,數據,xlev = xlev)中的錯誤:變量“train$list_outcome”的類型無效(NULL)
或以下內容:
list_outcome <- c("adequacy_ratio_total_percent")
X_train_matrix <- model.matrix(list_outcome[1] ~ ., train)[, -1]
model.frame.default(object, data, xlev = xlev) 中的錯誤:可變長度不同(為 'adequacy_ratio_total_percent' 找到)
如何從 list_outcome 中提取變量名並將其應用於 model.matrix 函數? 提前感謝您的任何建議!
這是一個與@user20650 使用相同想法的答案,但結果有多種可能性:
data(mtcars)
list_outcomes = c("qsec", "mpg")
Xmats <- lapply(list_outcomes, function(l){
model.matrix(reformulate(".", response=l), data=mtcars)
})
lapply(Xmats, head)
#> [[1]]
#> (Intercept) mpg cyl disp hp drat wt vs am gear carb
#> Mazda RX4 1 21.0 6 160 110 3.90 2.620 0 1 4 4
#> Mazda RX4 Wag 1 21.0 6 160 110 3.90 2.875 0 1 4 4
#> Datsun 710 1 22.8 4 108 93 3.85 2.320 1 1 4 1
#> Hornet 4 Drive 1 21.4 6 258 110 3.08 3.215 1 0 3 1
#> Hornet Sportabout 1 18.7 8 360 175 3.15 3.440 0 0 3 2
#> Valiant 1 18.1 6 225 105 2.76 3.460 1 0 3 1
#>
#> [[2]]
#> (Intercept) cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 1 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 1 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 1 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 1 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 1 8 360 175 3.15 3.440 17.02 0 0 3 2
#> Valiant 1 6 225 105 2.76 3.460 20.22 1 0 3 1
由reprex 包創建於 2022-06-28 (v2.0.1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.