ysarak
ysarak

Reputation: 11

Frequency count in R

I want it to display a frequency table of total domestic ( which includes Boston + salt lake city) and total frequency of international ( London + Shanghai). But it prints it out like this.

table$Category<-c("Domestic","International")
> table
  problem.6.data Freq      Category
1         Boston  136      Domestic
2         London  102 International
3 Salt Lake City  277      Domestic
4       Shanghai  184 International


I want an output of: 

 1. Domestic: 136+277
 2. International: 102+ 184

so, in the end the table should look like:

  1. Domestic: 413
  2. International: 286

What am I doing wrong?

Upvotes: 1

Views: 530

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

Maybe aggregate from base R can give the desired output

dfout <- aggregate(Freq ~ Category, df, sum)

such that

> dfout
       Category Freq
1      Domestic  413
2 International  286

Upvotes: 0

shortessay
shortessay

Reputation: 113

If you don't mind using the tidyverse, you could use group_by() and summarize():

library(tidyverse)

df <-
    data.frame(
        stringsAsFactors = FALSE,
        problem.6.data = c("Boston", "London", "Salt Lake City", "Shanghai"),
        Freq = c(136L, 102L, 277L, 184L),
        Category = c("Domestic", "International", "Domestic", "International")
    )

df %>% 
    group_by(Category) %>% 
    summarise(sum = sum(Freq))
#> # A tibble: 2 x 2
#>   Category        sum
#>   <chr>         <int>
#> 1 Domestic        413
#> 2 International   286

Created on 2020-03-19 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions