I need to convert a data frame into a matrix using the model.matrix function. The name of the original data frame is train, and the outcome variable of interest is called adequacy_ratio_total_percent. The below R code works.
X_train_matrix <- model.matrix(adequacy_ratio_total_percent ~ ., train)[, -1]
However, since my outcome variables may vary and I hope to simplify the changing of the outcome variables using the below code, which does not work.
list_outcome <- c("adequacy_ratio_total_percent")
X_train_matrix <- model.matrix(list_outcome ~ ., train)[, -1]
Error in model.frame.default(object, data, xlev = xlev) : variable lengths differ (found for 'adequacy_ratio_total_percent')
I also tried the following, which does not work either.
list_outcome <- c("adequacy_ratio_total_percent")
X_train_matrix <- model.matrix(train$list_outcome ~ ., train)[, -1]
Error in model.frame.default(object, data, xlev = xlev) : invalid type (NULL) for variable 'train$list_outcome'
Or the following:
list_outcome <- c("adequacy_ratio_total_percent")
X_train_matrix <- model.matrix(list_outcome[1] ~ ., train)[, -1]
Error in model.frame.default(object, data, xlev = xlev) : variable lengths differ (found for 'adequacy_ratio_total_percent')
How can I extract the variable name from list_outcome and apply it to the model.matrix function? Thank you in advance for any advice!
Here's an answer that uses the same idea as @user20650, but with multiple possibilities for outcomes:
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
Created on 2022-06-28 by the reprex package (v2.0.1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.