How do you pivot data from a list of data frames in R?

前端 未结 3 1728
野趣味
野趣味 2021-01-25 05:22

Let\'s say I have a list of data frames ldf:

df1 <- data.frame(date = c(1,2), value = c(4,5))
df2 <- data.frame(date = c(1,2), value = c(4,5))
ldf <- li         


        
3条回答
  •  花落未央
    2021-01-25 06:04

    If these rows were all in the same data frame, you would use aggregate to do the sum. You can combine them with rbind so they are in the same data frame:

    aggregate(value ~ date, data=do.call(rbind, ldf), FUN=sum)
      date value
    1    1     8
    2    2    10
    

    If the date columns in all the data frames are identical, you can easily use Reduce to do the sum:

    Reduce(function(x, y) data.frame(date=x$date, value=x$value+y$value), ldf)
      date value
    1    1     8
    2    2    10
    

    This should be a lot faster than rbind-ing the data together and aggregating.

提交回复
热议问题