简体   繁体   中英

Obtain the aggregated frequencies from data frame in R

I have a data frame which contains three items and one column for the frequency over different time periods as follow:

Col1    Col2        Col3    FREQUENCY   INTERVAL 
A       item1      CLASS1    4             1
A       item2      CLASS2    10            1
B       item2      CLASS1    5             1
B       item3      CLASS3    2             1
A       item1      CLASS1    8             2
C       item4      CLASS2    9             2
B       item2      CLASS1    3             3
C       item4      CLASS2    7             3

Now I want to aggregate the frequencies for the first three columns, I tried: df<-%>% count(col1,col2,col3,sort =TRUE) but it did not work in this situation. The expected result is:

Col1    Col2        Col3    TOTAL_FREQUENCY   
A       item1      CLASS1   12            
A       item2      CLASS2   10            
B       item2      CLASS1    8             
B       item3      CLASS3    2                       
C       item4      CLASS2   16                        

any suggestion?

A solution using dplyr . We can also replace group_by_at(vars(starts_with("Col"))) with group_by(Col1, Col2, Col3) . The count function is to count the number of occurrence. In this case, we need the sum function with summarise .

library(dplyr)

df2 <- df %>%
  group_by_at(vars(starts_with("Col"))) %>%
  summarise(TOTAL_FREQUENCY = sum(FREQUENCY)) %>%
  ungroup()
df2
# # A tibble: 5 x 4
#    Col1  Col2   Col3 TOTAL_FREQUENCY
#   <chr> <chr>  <chr>           <int>
# 1     A item1 CLASS1              12
# 2     A item2 CLASS2              10
# 3     B item2 CLASS1               8
# 4     B item3 CLASS3               2
# 5     C item4 CLASS2              16

DATA

df <- read.table(text = "Col1    Col2        Col3    FREQUENCY   INTERVAL 
A       item1      CLASS1    4             1
                 A       item2      CLASS2    10            1
                 B       item2      CLASS1    5             1
                 B       item3      CLASS3    2             1
                 A       item1      CLASS1    8             2
                 C       item4      CLASS2    9             2
                 B       item2      CLASS1    3             3
                 C       item4      CLASS2    7             3",
                 header = TRUE, stringsAsFactors = FALSE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM