Dynamic columns on the right side of mutate

I have a dataframe Df which looks like this:

Df = data.frame(x1 = c(1, 3, 2),
x2 = c(1, 4, 2),
x3 = c(2, 5, 6),
x4 = c(2, 1, 2),
x5 = c(4, 2, 3),
x6 = c(5, 3, 1))

Df
x1 x2 x3 x4 x5 x6
1 1 1 2 2 4 5
2 3 4 5 1 2 3
3 2 2 6 2 3 1

Then I have a loop, where I will create new columns with a dynamic column on the right side of the mutate-operation, that depends on another column of Df:

for (i in c(1:3)) {
Df <- Df %>% mutate(!!paste0("x",i + 3) := !!sym(paste0("x", i + x1)))
}

Then I get the following error:
Error in paste0("x", i + x1) : Object 'x1' not found

How can I solve this Problem?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.