1

我希望它显示国内总频率(包括波士顿+盐湖城)和国际总频率(伦敦+上海)的频率表。但它会像这样打印出来。

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

所以,最后表格应该是这样的:

  1. 国内:413
  2. 国际:286

我究竟做错了什么?

4

2 回答 2

1

如果您不介意使用 tidyverse,可以使用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

reprex 包(v0.3.0)于 2020-03-19 创建

于 2020-03-19T05:42:08.037 回答
0

也许aggregate从基础 R 可以提供所需的输出

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

这样

> dfout
       Category Freq
1      Domestic  413
2 International  286
于 2020-03-19T09:23:16.673 回答