简体   繁体   中英

Using lapply in R to loop through a list of data.frames in R

I have a dataframe as seen below, image due to size constraints:

瓶颈列表

So my goal is to take bottleneck_list which is a list of dataframes and using lapply, run the same analyses on all dataframes. They are custom but I am struggling to get it to run through each df.

test is bottleneck_list[[1]]

Here is a sample of the functions

  test2 <- test %>% 
  mutate(early_startTime = startTime - 300) %>% 
  mutate(id = rownames(test))

loop <- lapply(1:nrow(test), function(x) {
  neck_row <- test[x,]
  
  test_list <- test[which(test$startTime == bottleneck_row$endTime),]
})
match <- do.call(rbind,loop)

events * match

So basically each dataframe must have several operations done to it.

Here's what I tried:

list_alt <- lapply(bottleneck_list, sapply, function(x) {

  test <- bottleneck_list[[x]]
  
  test2 <- test %>% 
  mutate(early_startTime = startTime - 300) %>% 
  mutate(id = rownames(test))


loop <- lapply(1:nrow(test), function(x) {
  neck_row <- test[x,]
  
  test_list <- test[which(test$startTime == bottleneck_row$endTime),]
})
match <- do.call(rbind,loop)

match
})

But doesn't work. The end result should be all my dataframes from this list be a list of those dataframes with two more variables.

EDIT: I need to reference bottleneck_list[[1]] for this to work. 在此处输入图像描述

If it is aa list of data.frames, loop over the list with map , and mutate to create new columns in each of the data.frame s

library(purrr)
library(dplyr)
bottleneck_list2 <- map(bottleneck_list, ~ .x %>%
          mutate(early_startTime = startTime - 300, id = row_number()))

Or using lapply from base R

bottleneck_list2 <- lapply(bottleneck_list, function(test)
       transform(test, early_startTime = startTime - 300, id = row.names(test)))

If we want to do some transformations

 lapply(bottleneck_list, function(test){
        row.names(test) <- NULL
        test$somecol <- test$col1 + 24
        test
         })    

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