I have a dataframe that similar to this: (in fact, 16 in a for-loop)
head(data) # A tibble: 1 x 4 AAA AAC AB AC 1 18 25 39 9 2 20 25 30 7 I want to dynamically change all column names based on the column's original names, something like this (I've tried with str_glue, but I get an error):
### I have a for-loop: (NOT WORKING) (this is a part of the loop) assign(str_glue("df_{str_sub(data[i], 23, - 5)}"), read.delim(data[i], sep = ",", header = T) %>% mutate(ID = Participants, str_glue("New_{str_sub(data[i], 23, - 5)}_AAA") = AAA, str_glue("New_{str_sub(data[i], 23, - 5)}_AAB") = AAC, str_glue("New_{str_sub(data[i], 23, - 5)}_AB") = AB, str_glue("New_{str_sub(data[i], 23, - 5)}_AC") = AC) Desired output:
### Note: ### depending on the index-i, ### str_glue("New_{str_sub(data[i], 23, - 5)}_AAA") will get me either 50,100 or 150 ### desired output for i = 1 New_50_AAA New_50_AAC New_50_AB New_50_AC 1 18 25 39 9 2 20 25 30 7 I'm sure that there's an elegant way to do that. I've seen some related posts, but none seemed to help me. Any ideas? Thanks :)
PS: If there's also a way to dynamically repeat the original's column's name without repeating it with str_, that would be perfect, it would save me 4 lines
EDIT
The whole loop looks like this:
"data" is a list of 16 .txt files, each one is called "xxxxxxxxx_xx_50.txt", "xxxxxxxxx_xx_100.txt" (so on)
for (i in 1:length(data)) { if (grepl("xxxxxxxxx_x1_.txt$", data[i])) { assign(str_glue("df_narr{str_sub(data[i], 23, - 5)}"), read.delim(data[i], sep = ",", header = T) %>% mutate(ID = Participants, str_glue("New_1{str_sub(data[i], 23, - 5)}_AAA") = AAA, str_glue("New_1{str_sub(data[i], 23, - 5)}_AAB") = AAC, str_glue("New_1{str_sub(data[i], 23, - 5)}_AB") = AB, str_glue("New_1{str_sub(data[i], 23, - 5)}_AC") = AC) %>% mutate_if(is.numeric, round, digits = 2)) } else if (grepl("xxxxxxxxx_x2_.txt$", data[i])) { assign(str_glue("df_narr{str_sub(data[i], 23, - 5)}"), read.delim(data[i], sep = ",", header = T) %>% mutate(ID = Participants, str_glue("New_2{str_sub(data[i], 23, - 5)}_AAA") = AAA, str_glue("New_2{str_sub(data[i], 23, - 5)}_AAB") = AAC, str_glue("New_2{str_sub(data[i], 23, - 5)}_AB") = AB, str_glue("New_2{str_sub(data[i], 23, - 5)}_AC") = AC) %>% mutate_if(is.numeric, round, digits = 2)) } }
names(data) <- paste0("New_50_", names(data)). Creating multiple objects in the global env is not recommended. You could read all those data into a list and rename if needed