Reputation: 51
Is there a way to re-write the counter for-loop below using lapply/map (or sapply), but without using the "<<-" assignment operator?
I have a list of data frames (list_of_dfs
) from which I need to determine the total number of rows contained in the entire list of data frames. The code below works fine, but I want to know if I can get away without using a for-loop and not using the scoping assignment operator "<<-" to count the total number of rows.
Counter for-loop:
count <- 0
for(df in list_of_dfs){
count <- count + nrow(df)
}
The purrr::map function below does the trick, but I would like to avoid the "<<-" operator. purrr::walk, lapply and sapply gets to the same result.
count <- 0
map(list_of_dfs, function(x){
count <<- count + nrow(x)
})
It just seems sloppy...like some backyard workaround. Any advice would be appreciated.
Upvotes: 1
Views: 120
Reputation: 887831
We an use sum
library(tidyverse)
map_int(list_of_dfs, nrow) %>%
sum
Or with sapply
sum(sapply(list_of_dfs, nrow))
Upvotes: 3