通过分组汇总数据时出现“无法创建对不可调用对象的调用”错误

'Can't create call to non-callable object' error while summarizing data by grouping

我有以下数据框:

df <- data.frame(NR_HH = c('HH1','HH1','HH1','HH1','HH2','HH2'), ID = c(11,12,13,14,21,22), Age = c(28,25,16,4,45,70), Fem_Adult = c('FALSE','TRUE','FALSE','FALSE', 'TRUE','TRUE'),Male_Adult = c('TRUE','FALSE','FALSE','FALSE', 'FALSE','FALSE'), School_Child = c('FALSE','FALSE','TRUE','FALSE', 'FALSE','FALSE'), Preschool_Child = c('FALSE','FALSE','FALSE','TRUE', 'FALSE','FALSE'))

#  NR_HH ID Age Fem_Adult Male_Adult School_Child Preschool_Child
#1   HH1 11  28     FALSE       TRUE        FALSE           FALSE
#2   HH1 12  25      TRUE      FALSE        FALSE           FALSE
#3   HH1 13  16     FALSE      FALSE         TRUE           FALSE
#4   HH1 14   4     FALSE      FALSE        FALSE            TRUE
#5   HH2 21  45      TRUE      FALSE        FALSE           FALSE
#6   HH2 22  70      TRUE      FALSE        FALSE           FALSE

我想按 NR_HH 对这些数据进行分组,并构建一个新的数据框,显示每个家庭中成年女性、成年男性、学龄儿童和学龄前儿童的数量。我想得到这样的东西:

#  NR_HH Fem_Adult Male_Adult School_Child Preschool_Child
#1   HH1         1          1            1               1
#2   HH2         2          0            0               0

我尝试了以下代码:

df_summary =df%>%group_by(NR_HH)%>%summarise_if(is.logical, sum)

但是我得到这个错误:

Error: Can't create call to non-callable object

问题出在列类型上。这些是 factor 列,通过引用 'TRUE'/'FALSE' 产生 character 类型。但是,默认情况下 data.frame 调用使用 stringsAsFactors = TRUE。因此,我们得到这些列的 factor class。这可以通过简单地取消引用 TRUE/FALSE 输入来避免。假设输入已经被引用,然后将其转换为 logicalas.logical 然后通过 'NR_HH'

分组后得到 sum
df %>%
   mutate_at(4:7, as.logical) %>% 
   group_by(NR_HH) %>% 
   summarise_if(is.logical, sum)
# A tibble: 2 x 5
#  NR_HH Fem_Adult Male_Adult School_Child Preschool_Child
#   <fct>     <int>      <int>        <int>           <int> 
# 1 HH1           1          1            1               1
# 2 HH2           2          0            0               0