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

夙愿已清 提交于 2019-12-01 12:55:05

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 )

is it good for you ?

    library(dplyr)

    #matrices replication 
    iris1=iris
    iris2=iris
    iris3=iris

    #list of combinations: apply is tricky for array input
    irises=matrix(c("iris1","iris2","iris3"), ncol=1)

    #function design
    Funct<-function(df_name){

      df=get(df_name)
      df %>% mutate(Sepal=rowSums(select(.,starts_with("Sepal"))),
                    Length=rowSums(select(.,ends_with("Length"))),
                    Width=rowSums(select(.,ends_with("Width"))))
    }

    apply(irises,MARGIN=2, Funct)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!