I have a dataset and a vector of column names that I want to apply within a while loop. I can write code so it will put the number of iterations in the column name (eg, n_1, n_2), but when I try to get it to pull the value (eg, a, b), I get various errors (detailed below).
Here's my sample dataset and what I want:
#set up
library(dplyr)
my_new_cols <- c("a", "b", "c")
current_data <- tibble(id = c(1:4),
score = c(10, 20, 30, 40))
#desired output
current_data <- tibble(id = c(1:4),
score = c(10, 20, 30, 40),
n_a = c("a 10", "a 20", "a 30", "a 40"),
n_b = c("b 10", "b 20", "b 30", "b 40"),
n_c = c("c 10", "c 20", "c 30", "c 40"))
And here are my many attempts. This first one runs, but instead of giving n_a, it gives n_1 (the index). It also weirdly gives column called 'n_`, and the output is a duplicate of n_3.
i = 1
while(i <= length(my_new_cols)) {
current_data <- current_data %>%
mutate("n_{{i}}" := paste(my_new_cols[i], score))
i <- i 1
}
I also tried so many combinations calling in my_new_cols where you define column names, such as "n_{{my_new_cols[i]}}"
, "n_{{.data[i]}}"
, and "n_{{my_new_cols$i}}"
, all of which result in errors, most commonly
Error in local_error_context(dots = dots, .index = i, mask = mask) : promise already under evaluation: recursive default argument reference or earlier problems?
i = 1
while(i <= length(my_new_cols)) {
current_data <- current_data %>%
mutate("n_{{my_new_cols[i]}}" := paste(my_new_cols[i], score))
i <- i 1
}
What's going on and how do I get the value rather than the index to show?
CodePudding user response:
If you change "n_{{my_new_cols[i]}}"
to "n_{my_new_cols[i]}"
your code works as expected.
i = 1
while(i <= length(my_new_cols)) {
current_data <- current_data %>%
mutate("n_{my_new_cols[i]}" := paste(my_new_cols[i], score))
i <- i 1
}
Or try using a for loop instead, as the code is easier to understand.
for(i in my_new_cols) {
current_data <- current_data %>%
mutate("n_{i}" := paste(i, score))
}