将dplyr summarise_if()与谓词一起使用

时间:2019-08-26 13:07:37

标签: r group-by dplyr summarize

我想计算总和(is.NA)与所有观测值之比> = 0.5 或不适用NA的日子的x1和x2的均值。

数据:

library(lubridate)
library(dplyr)

x = seq(length.out= 10)
x[seq(1,11,5)] <- NA
data = data.frame(
    tseq = seq(from = Sys.time(), length.out = 11, by = "12 hours"),
    x1 = x,
    x2 = x
    )

means = data %>% group_by(tseq=floor_date(tseq, "days")) %>%
    summarise_all(list( mean = ~ mean(., na.rm = TRUE)))

ratio = data %>% group_by(tseq=floor_date(tseq, "days")) %>%
    summarise_all(list( ratio = ~ sum(is.na(.)) / n()))
> ratio
  tseq                x1_ratio x2_ratio
1 2019-08-26 00:00:00      1        1  
2 2019-08-27 00:00:00      0        0  
3 2019-08-28 00:00:00      0        0  
4 2019-08-29 00:00:00      0.5      0.5
5 2019-08-30 00:00:00      0        0  
6 2019-08-31 00:00:00      0.5      0.5

所以在这里 2019-08-26、2019-08-29、2019-08-31 日期会很有效。 在向量中,我可以通过功能来实现

isEnough = function(x){
    # is there enough values to calculate mean
    if (sum(is.na(x)) / length(x) < 0.5){
        return(FALSE)
    }
    else return(TRUE)
}

对于数据框,我找不到解决方案。到目前为止,我已经尝试过

data %>% group_by(tseq=floor_date(tseq, "days")) %>%
    summarise_if(.predicate =  isEnough(~ sum(is.na(.)), ~n()),
    .funs = list( mean = ~ mean(., na.rm = TRUE)))
Error in naCount/xLength : non-numeric argument to binary operator

data %>% group_by(tseq=floor_date(tseq, "days")) %>%
    summarise_if(.predicate = list( ~ sum(is.na(.)) / n() > 0.5),
    .func = list( mean = ~ mean(., na.rm = TRUE)))
Error: n() should only be called in a data context

data %>% group_by(tseq=floor_date(tseq, "days")) %>%
    summarise_if(.predicate = (~ sum(is.na(.)) / ~n() > 0.5),
    .func = list( mean = ~ mean(., na.rm = TRUE)))
Error in sum(is.na(.))/~n() > 0.5 : 
  non-numeric argument to binary operator

1 个答案:

答案 0 :(得分:1)

summarise_if用于选择。将其视为summarise_at的派生形式,您可以在其中指定要在其上使用某些功能的列。

您似乎想分别计算x1x2的均值 ,但是在相同条件下,我首先将两列汇总为一tidyr的{​​{1}}:

gather

最后一步是清理它,并将其包装回格式:

library(tidyr)
data %>% gather(x, val, x1, x2) %>% 
  group_by(tseqs=floor_date(tseq, "days"), x) %>% 
  summarise(
    ratio=sum(is.na(val))/n(), 
    mean=mean(val, na.rm=TRUE)*ifelse(ratio >= 0.5, NA, 1)
  )
# A tibble: 12 x 4
# Groups:   tseqs [?]
   tseqs               x     ratio  mean
   <dttm>              <chr> <dbl> <dbl>
 1 2019-08-26 00:00:00 x1      1   NaN  
 2 2019-08-26 00:00:00 x2      1   NaN  
 3 2019-08-27 00:00:00 x1      0     2.5
 4 2019-08-27 00:00:00 x2      0     2.5
 5 2019-08-28 00:00:00 x1      0     4.5
 6 2019-08-28 00:00:00 x2      0     4.5
 7 2019-08-29 00:00:00 x1      0.5  NA  
 8 2019-08-29 00:00:00 x2      0.5  NA  
 9 2019-08-30 00:00:00 x1      0     8.5
10 2019-08-30 00:00:00 x2      0     8.5
11 2019-08-31 00:00:00 x1      0.5  NA  
12 2019-08-31 00:00:00 x2      0.5  NA