簡體   English   中英

dplyr:為什么不使用 summarise() 匯總案例?

[英]dplyr: Why are cases not summarized using summarise()?

我有

> head(df,7)
        date pos cons_week
1 2020-03-30 313       169
2 2020-03-31 255       169
3 2020-04-01 282       169
4 2020-04-02 382       169
5 2020-04-03 473       169
6 2020-04-04 312       169
7 2020-04-05 158       169

pos表示每天的陽性 COVID 病例數。 cons_week是自鎖定以來的連續周數。 因此,每個cons_week都有 7 個pos條目。 我想總結一下,所以我有每周的pos總數。

我嘗試了不同的版本,比如

df %>% group_by(cons_week) %>%
  summarise(n = n())

或者

df %>% group_by(cons_week, pos) %>%
  summarise(n = sum())

預期 output

cons_week     n
169        2175 
170        1651
171        1179

數據

df <- structure(list(date = structure(c(18351, 18352, 18353, 18354, 
                                  18355, 18356, 18357, 18358, 18359, 18360, 18361, 18362, 18363, 
                                  18364, 18365, 18366, 18367, 18368, 18369, 18370, 18371), class = "Date"), 
               pos = c("313", "255", "282", "382", "473", "312", "158", 
                       "424", "347", "301", "140", "142", "140", "157", "156", "258", 
                       "199", "178", "168", "106", "114"), cons_week = c(169, 169, 
                                                                         169, 169, 169, 169, 169, 170, 170, 170, 170, 170, 170, 170, 
                                                                         171, 171, 171, 171, 171, 171, 171)), row.names = c(NA, 21L
                                                                         ), class = "data.frame")

因為pos是您的df中的character 您需要先將其轉換為numeric 例如:

library(dplyr)

df %>% 
        mutate(pos = as.numeric(pos)) %>% 
        group_by(cons_week) %>% 
        summarise(n = sum(pos))

或者:

df %>% 
        group_by(cons_week) %>% 
        summarise(n = sum(as.numeric(pos)))

Output:

  cons_week     n
      <dbl> <dbl>
1       169  2175
2       170  1651
3       171  1179

利用:

df %>% group_by(cons_week) %>% 
    summarise(n = sum(as.numeric(pos)))

或之前:

df$pos <- as.numeric(df$pos)
df %>% group_by(cons_week) %>%
   summarise(n = sum(pos))

問題是pos是字符類型( class ),而不是numeric

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM