1

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)
2
  • Can you please put the name of the package you used at the begining of your code to make it more reproductible. Thks Commented Jul 16, 2013 at 21:07
  • Can't you just pass a formula as argument? Commented Jul 16, 2013 at 21:58

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.