按行将功能应用于数据框列表,返回数据框列表

时间:2020-04-16 16:02:56

标签: r apply lapply

这是可行的,但是似乎很笨拙。是否有更直接的方法?我有一个数据帧列表,我想对每个行应用一个函数,该函数将一些东西返回到数据帧中。

 #Some fake data
   df1=data.frame(a=rnorm(100,5,1), b=rnorm(100,5,1))
   df2=data.frame(c=rnorm(100,5,1), d=rnorm(100,5,1), e=rnorm(100,5,1))
   mylist<-list(df1,df2)
   names(mylist)<-c("df1","df2")

 #a function this function will not be about sums, it is just the simplest 
 # function applied across rows I can come up with. 
   lfun<-function(x){apply(x, 1, FUN=function(y){
   out<-data.frame(out0=y[1],
                   out1=sum(y[2:length(y)]), 
                   out2=sum(y[2:length(y)])^2)})
    }

 #how it is currently being invoked and turned into df output
   dfout<-lapply(mylist, lfun)
   lapply(dfout, FUN=function(x){do.call("rbind", x)})

1 个答案:

答案 0 :(得分:0)

考虑rowSumsapply + sum的包装):

lfun <- function(df) {
   out <- data.frame(out0 = df[,1],
                     out1 = rowSums(df[2:length(df)]), 
                     out2 = rowSums(df[2:length(df)])^2)
}

newlist <- lapply(mylist, lfun)

为避免两次重新计算rowSums,请考虑使用transform

lfun <- function(df) {
   out <- transform(data.frame(out0 = df[,1],
                               out1 = rowSums(df[2:length(df)])), 
                    out2 = out1^2)
}

newlist2 <- lapply(mylist, lfun)

identical(newlist1, newlist2)
# [1] TRUE