Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply same operation to multiple data frames in dplyr-R?

I would like to apply the same operation to multiple data frames in 'R' but cannot get how to deal with this matter.

This is an example of pipe operation in dplyr:

library(dplyr)

    iris %>% mutate(Sepal=rowSums(select(.,starts_with("Sepal"))),
                    Length=rowSums(select(.,ends_with("Length"))),
                    Width=rowSums(select(.,ends_with("Width"))))
iris2 <- iris
iris3 <- iris

Could you suggest how to apply the same pipe function to iris, iris2 and isis3? I need to use dplyr piping operation.

I suppose map function may help but as I have not fully understand its concept, I got errors to apply it.

Sample script:

library(purrr)

iris.set <- c(iris,iris2,iris3)
map(iris.set, ~ . %>% mutate(Sepal=rowSums(select(.,starts_with("Sepal"))),
                Length=rowSums(select(.,ends_with("Length"))),
                Width=rowSums(select(.,ends_with("Width")))))
like image 250
HSJ Avatar asked Jan 28 '23 22:01

HSJ


1 Answers

If you turn your operation into a function:

library(dplyr)
my_fun <- function(x) { 
      x %>%       
          mutate(Sepal=rowSums(select(.,starts_with("Sepal"))),
          Length=rowSums(select(.,ends_with("Length"))),
          Width=rowSums(select(.,ends_with("Width"))))
}

You can pipe a list of data frames to it easily:

result <- list( iris, iris2, iris3 ) %>%
    lapply( my_fun )
like image 128
rosscova Avatar answered Apr 18 '23 18:04

rosscova