Aggregate multiple rows of the same data.frame in R based on common values in given columns

后端 未结 5 907
情歌与酒
情歌与酒 2021-02-02 17:29

I have a data.frame that looks like this:

# set example data
df <- read.table(textConnection(\"item\\tsize\         


        
相关标签:
5条回答
  • 2021-02-02 17:56
    df$value <- ave(df$value,df$item,FUN=mean)
    df[!duplicated(df$item),]
    
      item size weight value
    1    A    2      3     5
    3    B    1      2     3
    4    C    3      2     1
    
    0 讨论(0)
  • 2021-02-02 17:57

    Here is the solution using the ddply from plyr package:

    library(plyr)
    ddply(df,.(item),colwise(mean))
      item size weight value
    1    A    2      3     5
    2    B    1      2     3
    3    C    3      2     1
    
    0 讨论(0)
  • 2021-02-02 17:58

    Nowadays, this is what I would do:

    library(dplyr)
    
    df %>%
      group_by(item, size, weight) %>%
      summarize(value = mean(value)) %>%
      ungroup
    

    This yields the following result:

    # A tibble: 3 x 4
       item  size weight value
      <chr> <int>  <int> <dbl>
    1     A     2      3     5
    2     B     1      2     3
    3     C     3      2     1
    

    I will leave the accepted answer as such as I specifically asked for aggregate, but I find the dplyr solution the most readable.

    0 讨论(0)
  • 2021-02-02 18:05
    aggregate(value ~ item + size + weight, FUN = mean, data=df)
    
      item size weight value
    1    B    1      2     3
    2    C    3      2     1
    3    A    2      3     5
    
    0 讨论(0)
  • 2021-02-02 18:14

    The data.table solution...

    require(data.table)
    DT <- data.table(df)
    
    DT[ , lapply(.SD , mean ) , by = item ]
       item size weight value
    1:    A    2      3     5
    2:    B    1      2     3
    3:    C    3      2     1
    
    0 讨论(0)
提交回复
热议问题