Reputation: 1105
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.
Upvotes: 1
Views: 2303
Reputation: 886938
If it is a a 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
})
Upvotes: 2