Reputation: 347
I have a loop from 1 to 5 and have to essentially create var1 to var5 within the loop. My current code looks something like
for (i in 1:5) {
iris <- iris %>%
mutate(paste0("var_", i) = Sepal.Length + i)
}
However, this returns an error
Error: unexpected '=' in:
" iris <- iris %>%
mutate(paste0("var_", i) ="
> }
Error: unexpected '}' in "}"
How can I dynamically name variables within the mutate statement?
Upvotes: 1
Views: 167
Reputation: 7423
for (i in 1:5) {
iris <- iris %>%
mutate("{paste0('var_', i)}" := Sepal.Length + i)
}
This uses syntax from the glue
package to dynamically rename.
Upvotes: 2