Home > Blockchain >  Generate Variable Inside Loop Dplyr
Generate Variable Inside Loop Dplyr

Time:02-10

I am trying to generate a variable inside a loop using mutate. This variable should simply be the concatenate of the word period and the loop iteration number i.

Unfortunately the following code generates the variable p instead of period1, period2, and so on.

Does anyone know how can I get the name as period1 instead of simply p?

The expected outcome is the following:

Fr1 <- data.frame (v1  = c("a", "b", "c"),
                  v2 = c("1", "2", "a"),
                  v3 = c("2", "4", "c"),
                  period1 = c("Yes", "Yes", "Yes")
)

Fr2 <- data.frame (v1  = c("a", "b", "c"),
                   v2 = c("1", "2", "a"),
                   v3 = c("2", "4", "c"),
                   period2 = c("Yes", "Yes", "Yes")
)
countries <- c("Fr", "Be", "De")
df <- data.frame (v1  = c("a", "b", "c"),
                  v2 = c("1", "2", "a"),
                  v3 = c("2", "4", "c")
)

for(c in countries) {
  for(i in 1:6) {
     p <- paste0("period", i)  
     new <- "Yes"
     a <- df %>%
       mutate(p = new)
     assign(paste0(c,i), a)  
  }
}    

CodePudding user response:

I think you are looking for something like this -

library(tidyverse)

countries <- c("Fr", "Be", "De")
df <- data.frame (v1  = c("a", "b", "c"),
                  v2 = c("1", "2", "a"),
                  v3 = c("2", "4", "c")
)

for(c in countries) {
  for(i in 1:6) {
    p <- paste0("period", i)  
    new <- "Yes"
    a <- df %>%  mutate(!!p := new)
    assign(paste0(c,i), a)  
  }
}    

However, it is not a good practice to create so many dataframes in global environment, use lists instead.

Something like this -

pmap(expand_grid(countries, n), function(...) {
  df %>% mutate(!!paste0("period", ..2) := 'new')
})
  • Related