Reputation: 115
This is pretty simple, but I am wondering why the following doesnt work.
Works
myvars=c("JourneyTravelTime","PaxType")
formula=as.formula(paste("SumAmountBooked~",paste(myvars,collapse="+")))
Output (text)
SumAmountBooked ~ JourneyTravelTime + PaxType
Doesnt work
i=1
formula=as.formula(paste("as.factor(Product",i,")",sep=""),paste(myvars,collapse="+"))
It then says object Product1 not found. I assume it is because I paste an object (i) with the other text that it looks for an object. is there a way to treat it as text anyways? I have tried wrapping as.character around different parts and it doesnt help.
Upvotes: 0
Views: 1433
Reputation: 17359
Careful inspection of your code will show that you are not actually passing a formula-like string to as.formula
in the example that isn't working. Let's step through and add some structure to your code. We will put each argument to a function on its own line.
In your first example, which works, you are passing the strings "SumAmountBooked~"
and "JourneyTravelTime+PaxType"
into paste
. The full string can be coerced to a valid formula.
myvars = c("JourneyTravelTime",
"PaxType")
# Notice that you have only ONE argument to `as.formula`
formula =
as.formula(
paste("SumAmountBooked~",
paste(myvars,
collapse="+"))
)
In your next example, however, you are passing two strings to as.formula
. This is causing R to look for the object as.factor(Product1)
in the environment "JourneyTravelTime+PaxType"
. Since there is no environment of that name, the coercion to a formula fails.
i = 1
# Now you have TWO arguments to `as.formula`.
# The second argument is the environment in which to find the first.
# You also have no '~'
formula=
as.formula(
paste("as.factor(Product",
i,
")",
sep=""),
paste(myvars,
collapse="+")
)
One way to get the desired result would be as follows:
as.formula(
paste0(
paste0("as.factor(Product",
i,
")"),
" ~ ",
paste(myvars,
collapse = "+")
)
)
Personally, I'd be inclined to use sprintf
to avoid putting in so many paste
commands. This can help keep the structure of your desired string together while you substitute in the pieces where the %s
's go.
as.formula(
sprintf("as.factor(Product%s) ~ %s",
i,
paste0(myvars, collapse = "+"))
)
Upvotes: 2