简体   繁体   English

当有 NA 值时,如何使用 dplyr 返回所有数字列的分组总和?

[英]How to use dplyr to return the grouped sum of all numeric columns when there are NA values?

I'm was attempting to sum all numeric columns using dplyr's group_by and summarise functions as below.我正在尝试使用 dplyr 的 group_by 对所有数字列求和,并汇总如下函数。 I didn't understand the error returned from the summarise function and cannot seem to find a similar example on stack overflow ... however after two members pointed out my error in making the example data I found that the code I had to prepared to provide a grouped summary sum report was correct!我不明白 summarise 函数返回的错误,并且似乎找不到堆栈溢出的类似示例......但是在两个成员指出我在制作示例数据时出错后,我发现我必须准备提供的代码分组汇总总和报告是正确的!

    # Dummy data
    a <- c(1, NA, 1, NA, 1, 1)
    b <- c( NA, 1, NA, 1, NA, NA)
    c <- c( 1, 1, 1, NA, 1, 1)
    d <- c( 1, 1, 1, NA, 1, NA)
    e <- c( NA, 1, 1, NA, 1, 1)
    f <- c( 1, NA, 1, NA, 1, 1)
    
# Make a tibble
tmp <- bind_cols(a, b, c, d, e) 
names(tmp) <- c("A", "B", "C", "D", "E")

ID <- c("X", "X", "Y", "Y", "Z", "Z")

tmp <-bind_cols(ID, tmp)
names(tmp)[1] <- "ID"

    # Return a sum report
    tmp %>% 
      group_by(ID) %>% 
      summarise(across(everything(), ~ sum(.x, na.rm = TRUE)))

    # A tibble: 3 × 6
      ID        A     B     C     D     E
      <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
    1 X         1     1     2     2     1
    2 Y         1     1     1     1     1
    3 Z         2     0     2     1     2

It's best to avoid defining a vector with different data types because R will convert the vector to a single data type.最好避免定义具有不同数据类型的向量,因为 R 会将向量转换为单一数据类型。

I think you might want to create your data like this:我认为您可能希望像这样创建数据:

tmp = tibble(
         ID = c('X', 'X', 'Y', 'Y', 'Z', 'Z'),
         A = c(1, NA, 1, 1, NA, 1),
         B = c(NA, 1, 1, 1, 1, NA),
         C = c(1, NA, 1, 1, 1, 1),
         D = c(NA, 1, NA, NA, NA, NA),
         E = c(1, NA, 1, 1, 1, 1))

And then do:然后做:

tmp %>%
  group_by(ID) %>% 
  summarise(across(everything(), ~ sum(.x, na.rm = TRUE)))

To get:要得到:

# A tibble: 3 x 6
  ID        A     B     C     D     E
  <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 X         1     1     1     1     1
2 Y         2     2     2     0     2
3 Z         1     1     2     0     2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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