I need to recall the variable within the loop and the use that as my column name:
This is an example dataset:
mtcars.df <- mtcars
Expected output:
mtcars.df <- mtcars.df %>% add_column(a1 = sample (1:4, 32, replace = TRUE), b1 = sample (1:4, 32, replace = TRUE), c1 = sample (1:4, 32, replace = TRUE))
So a1, b1 and c1 need to be created within the loop and renamed to a1, b1 and c1. The names are longer (and different combinations) in the original dataset but this is defined in variable mpg.filename.
This is what I have tried so far: The 1st obviously doesn't give the desired result but it's just to show what I want to achieve.
mpg.filename <- c("a1.file", "b1.file", "c1.file")
for (i in mpg.filename) {
sample.name <- unlist(strsplit(as.character(i), '.', fixed = TRUE))[1]
mtcars.df$i <- sample (1:4, 32, replace = TRUE)
}
for (i in mpg.filename) {
sample.name <- unlist(strsplit(as.character(i), '.', fixed = TRUE))[1]
mtcars.df$temp.var <- sample (1:4, 32, replace = TRUE)
temp.name <- paste0 (sample.name) %>% rlang::parse_expr()
mtcars.df <- mtcars.df %>% rename (eval (sample.name) = temp.var)
}
for (i in mpg.filename) {
sample.name <- unlist(strsplit(as.character(i), '.', fixed = TRUE))[1]
mtcars.df$temp.var <- sample (1:4, 32, replace = TRUE)
temp.name <- paste0 (sample.name) %>% rlang::parse_expr()
mtcars.df <- mtcars.df %>% rename (syms(sample.name) = temp.var)
}
I have tried get
, as.symbol
, parse (text = "sample.name")
as well but didn't work either.
Thanks for the help. I have tried looking at other answers on forums but they do not seem to apply or work.
using eval() on string to access object attributes in R
call columns from inside a for loop in R