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

前端 未结 2 814
执笔经年
执笔经年 2021-01-14 17:07

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 operat

相关标签:
2条回答
  • 2021-01-14 17:40

    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 )
    
    0 讨论(0)
  • 2021-01-14 17:41

    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)
    
    0 讨论(0)
提交回复
热议问题