简体   繁体   中英

Using assignment operators to create multiple df within for-loop in R

I often use longitudinal data sets, summarise data and put together reports with the summary data in a side-by-side format. To do so, I generally run a chunk of code for the relevant years, create a data frame for each year, then use bind_cols to put the data together.

I am hoping to use a for-loop so I do not need to modify the code for each year. I am trying to use the assignment operator to create multiple data frames while running the loop. Here is my attempt that is not working:

d1 <- data.frame(Year = c(2019, 2019, 2019, 2018, 2018),
                 Group = c("a", "b", "b", "a", "c"))

years <- c(2019, 2018)


for (i in years){
  df <- filter(d1$Year == i) %>%
        group_by(Group) %>%
        summarise(n = n()) %>%
        rename(paste0("n_", i) = n)

  dat[[i]] <- df
}

Any assistance would be appreciated.

We can filter with %in% for multiple values instead of == and then take the 'count'

library(dplyr)
d1 %>%
   filter(Year %in% years) %>%
   count(Group, Year)

If we want to make multiple data.frames

d1 %>%
   filter(Year %in% years) %>%
   group_split(Year) %>%
   map(~ .x %>%
             count(Group))
  d1 <- data.frame(Year = c(2019, 2019, 2019, 2018, 2018),
                     Group = c("a", "b", "b", "a", "c"))

  years <- c(2019, 2018)


  for (i in years){

  df = d1 %>%
    filter(d1$Year == i) %>%
    group_by(Group) %>%
    summarize(now = n())

  assign(paste0("df_", i),df)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM