R- Referencing different dataframes in a loop

后端 未结 3 873
清酒与你
清酒与你 2021-01-27 02:43

I am brand new to R so if I\'m thinking about this completely wrong feel free to tell me. I have a series of imported dataframes on power plants, one of each year (Plant1987, Pl

3条回答
  •  一个人的身影
    2021-01-27 03:17

    Here are some codes to give you some ideas. I used the mtcars data frame as an example to create a list with three data frames. After that I used two solutions to add the year (2000 to 2002) to each data frame. You will need to modify the codes for your data.

    # Load the mtcars data frame
    data(mtcars)
    
    # Create a list with three data frames
    ex_list <- list(mtcars, mtcars, mtcars)
    
    # Create a list with three years: 2000 to 2002
    year_list <- 2000:2002
    

    Solution 1: Use lapply from base R

    ex_list2 <- lapply(1:3, function(i) {
    
      dt <- ex_list[[i]]
    
      dt[["Year"]] <- year_list[[i]]
    
      return(dt)
    })
    

    Solution 2: Use map2 from purrr

    library(purrr)    
    
    ex_list3 <- map2(ex_list, year_list, .f = function(dt, year){
    
      dt$Year <- year
    
      return(dt)
    })
    

    ex_list2 and ex_list3 are the final output.

提交回复
热议问题