R aggregate data.frame with date column

前端 未结 4 1128
挽巷
挽巷 2020-12-18 13:33

I have the data frame resambling the one in the below

Date       Expenditure Indicator
29-01-2011 5455        212
25-01-2012 5452        111
11-02-2011 365           


        
相关标签:
4条回答
  • 2020-12-18 13:58

    Or use dplyr:

    library(dplyr)
    
    dta %>%
      group_by(Date) %>%
      summarise(Tot.Expenditure = sum(Expenditure))
    
    0 讨论(0)
  • 2020-12-18 14:07

    Upgrade from base and use data.table instead to simplify (and speed up) your code/life:

    library(data.table)
    
    dt = as.data.table(dta)
    
    dt[, lapply(.SD, sum), by = Date]
    
    0 讨论(0)
  • 2020-12-18 14:08

    Indicate the variables you are trying to get the aggregate of in your aggregate statement, and this problem should be resolved:

    dta.sum <- aggregate(x = dta[c("Expenditure","Indicator")],
                         FUN = sum,
                         by = list(Group.date = dta$Date))
    

    EDITED TO ADD EXPLANATION: When you give the aggregate argument as just dta, aggregate attempts to apply the argument to every column. sum is not defined for date values in R, and therefore you are getting errors. You want to exclude the grouping column by using the code described above.

    0 讨论(0)
  • 2020-12-18 14:09
    df <- data.frame(c('29-01-2011', '25-01-2012', '11-02-2011'), c(5455, 5452, 365), c(212, 211, 5))
    colnames(df) <- c('Date', 'Expenditure', 'Indicator')
    colSums(df[2])
    
    #>Expenditure 
    #11272 
    
    0 讨论(0)
提交回复
热议问题