Adrian Mak
Adrian Mak

Reputation: 157

Refering to a column name in a formula with a string variable in R

I'm trying to reference the name of a column in a formula by using a variable target, which consists of pasted strings.

target = paste0("C","_inf")
model.matrix(target~., model.df)

This results in the error

Error in model.frame.default(object, data, xlev = xlev) :
  variable lengths differ

However, referencing the name of the column directly as in model.matrix(C_inf~., model.df) results in no such error and a perfectly fine model matrix. I guess this is caused by the type of target being chr, but I can't seem to figure out how to specify to use it as placeholder for a column name. Could someone tell me where I'm going wrong and how to approach fixing it? Thanks a lot!

Upvotes: 2

Views: 534

Answers (1)

akrun
akrun

Reputation: 887128

We can create the formula in paste or reformulate

model.matrix(reformulate(".", response = target), model.df)

Or with paste

model.matrix(as.formula(paste0(target, "~.")), model.df)

or can use glue

model.matrix(glue::glue("{target}~ ."), model.df)

Upvotes: 3

Related Questions