1

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?

1 Answer 1

2
for (i in 1:5) {
  iris <- iris %>%
    mutate("{paste0('var_', i)}" := Sepal.Length + i) 
}

This uses syntax from the glue package to dynamically rename.

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.