Dan KS
Dan KS

Reputation: 143

Pass string variable into R function

I want to pass a variable name into a function and can't seem to do it. Simply...

library (reshape)
test <- function(x) {
 cast(data, x ~ ., length)
}
test(ageg)

I get this kickback.

Error: Casting formula contains variables not found in molten data: x

I know it's simple but I can't find the answer.I want it to simply run

cast(data, ageg ~ ., length)

Upvotes: 1

Views: 3475

Answers (1)

asb
asb

Reputation: 4432

Try this:

test <- function (x) cast(data, as.formula(paste0(x , " ~ .")), length)

What you are trying to do is write a formula on the fly. However, a formula is possed on as quoted part of the language (IIRC). Therefore, your x is not evaluated but looked for in your data as x.

What this does on the other hand is to first create a character string by evaluating x in paste0. Then the string is converted to a formula using as.formula.

Upvotes: 2

Related Questions