【问题标题】:group_by and count number of rows a condition is met in Rgroup_by 和计数 R 中满足条件的行数
【发布时间】:2019-03-01 15:33:45
【问题描述】:

我有一个如下的数据表:

city         year    temp
Seattle      2019    82 
Seattle      2018    10 
NYC          2010    78 
DC           2011    71 
DC           2011    10 
DC           2018    60 

我想按cityyear 对它们进行分组,并从中创建一个新表 例如,西雅图有多少年的温度在 10 到 20 之间,它有多少年的温度在 20 到 30 之间,等等。

我该怎么做?

【问题讨论】:

  • cut创建新列

标签: r group-by conditional-statements


【解决方案1】:

我们可以使用cuttemp 分配到bins 并通过citytemp_range 进行汇总:

library(dplyr)

df %>%
  mutate(temp_range = cut(temp, breaks = seq(0, 100, 10))) %>%
  group_by(city, temp_range) %>%
  summarize(years = n_distinct(year))

输出:

# A tibble: 6 x 3
# Groups:   city [3]
  city    temp_range years
  <fct>   <fct>      <int>
1 DC      (0,10]         1
2 DC      (50,60]        1
3 DC      (70,80]        1
4 NYC     (70,80]        1
5 Seattle (0,10]         1
6 Seattle (80,90]        1

使用dplyr 0.8.0,我们还可以通过在group_by 中将新的.drop 参数设置为FALSE 来保持空因子水平:

df %>%
  mutate(temp_range = cut(temp, breaks = seq(0, 100, 10))) %>%
  group_by(city, temp_range, .drop = FALSE) %>%
  summarize(years = n_distinct(year))

输出:

# A tibble: 30 x 3
# Groups:   city [3]
   city  temp_range years
   <fct> <fct>      <int>
 1 DC    (0,10]         1
 2 DC    (10,20]        0
 3 DC    (20,30]        0
 4 DC    (30,40]        0
 5 DC    (40,50]        0
 6 DC    (50,60]        1
 7 DC    (60,70]        0
 8 DC    (70,80]        1
 9 DC    (80,90]        0
10 DC    (90,100]       0
# ... with 20 more rows

数据:

df <- structure(list(city = structure(c(3L, 3L, 2L, 1L, 1L, 1L), .Label = c("DC", 
"NYC", "Seattle"), class = "factor"), year = c(2019L, 2018L, 
2010L, 2011L, 2011L, 2018L), temp = c(82L, 10L, 78L, 71L, 10L, 
60L)), class = "data.frame", row.names = c(NA, -6L))

【讨论】:

  • 您是否知道如何计算像(10, 20), (10, 30), (10, 40) 这样的重叠区间的年数?所以,其实,我想知道已经有多少年了,超过10年,超过20年,超过30年
猜你喜欢
  • 2020-08-29
  • 1970-01-01
  • 2019-07-15
  • 2013-10-14
  • 2022-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多