繁体   English   中英

将字符转换为变量名

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM