mutate_at evaluation error when using group_by

妖精的绣舞 提交于 2019-12-05 23:17:13

The reason we are getting NA values is that the output we get from which is 3, but we grouped by 'Id' and so there are only 2 columns after that.

dftest %>%
     group_by(Id) %>% 
     mutate_at(which(names(dftest) %in% nacol)-1, funs(ifelse(is.na(.),0,.)))
# A tibble: 6 x 3
# Groups:   Id [6]
#      Id Month   RWA
#  <fctr> <dbl> <dbl>
#1   10_1     2 0.000
#2   10_2     3 0.000
#3   11_1     4 0.000
#4   11_2     6 1.579
#5   11_3     7 0.000
#6   12_1     8 0.379

The group_by is part is not needed here as we are changing NA values in other columns to 0

dftest %>%
    mutate_at(which(names(dftest) %in% nacol), funs(ifelse(is.na(.),0,.)))

It could be a bug and using the position based approach is sometimes risky. Better option would be to go with names

dftest %>%
    group_by(Id) %>% 
    mutate_at(intersect(names(.), nacol), funs(replace(., is.na(.), 0)))

NOTE: In all these cases, the group_by is not needed


Another option is replace_na from tidyr

dftest %>%
    tidyr::replace_na(as.list(setNames(0, nacol)))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!