使用group_时在计算错误时对_进行变异
mutate_at()与group_by()一起使用时,以及将列位置的数字向量作为第一个(.vars)参数输入时,显示计算错误使用group_时在计算错误时对_进行变异,r,dplyr,tidyverse,mutate,R,Dplyr,Tidyverse,Mutate,mutate_at()与group_by()一起使用时,以及将列位置的数字向量作为第一个(.vars)参数输入时,显示计算错误 使用R3.4.2和dplyr0.7.4版本时会出现问题 使用R3.3.2和dplyr0.5.0时工作正常 如果.vars是字符向量(列名),则可以正常工作 例如: # Create example dataframe Id <- c('10_1', '10_2', '11_1', '11_2', '11_3', '12_1') Month <- c(2,
- 使用
3.4.2和R
0.7.4版本时会出现问题dplyr
- 使用
3.3.2和R
0.5.0时工作正常dplyr
- 如果.vars是字符向量(列名),则可以正常工作
# Create example dataframe
Id <- c('10_1', '10_2', '11_1', '11_2', '11_3', '12_1')
Month <- c(2, 3, 4, 6, 7, 8)
RWA <- c(0, 0, 0, 1.579, NA, 0.379)
dftest = data.frame(Id, Month, RWA)
# Define column to fill NAs
nacol = c('RWA')
# Fill NAs with last period
dftest_2 <- dftest %>%
group_by(Id) %>%
mutate_at(which(names(dftest) %in% nacol),
funs(ifelse(is.na(.),0,.)))
更合理的例子说明了这个问题:
# Create example dataframe
Id <- c('10_1', '10_2', '11_1', '11_3', '11_3', '12_1')
Month <- c(2, 3, 4, 6, 7, 8)
RWA <- c(0, 0, 0, 1.579, NA, 0.379)
dftest = data.frame(Id, Month, RWA)
# Define column to fill NAs
nacol = c('RWA')
# Fill NAs with last period
dftest_2 <- dftest %>%
group_by(Id) %>%
mutate_at(which(names(dftest) %in% nacol),
funs(na.locf(., na.rm=F)))
#创建示例数据帧
Id我们得到NA值的原因是我们从中得到的输出是3,但是我们按“Id”分组,因此后面只有2列
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
这可能是一个bug,使用基于位置的方法有时是有风险的。更好的选择是使用名称
dftest %>%
group_by(Id) %>%
mutate_at(intersect(names(.), nacol), funs(replace(., is.na(.), 0)))
注意:在所有这些情况下,不需要使用groupby
另一个选项是从tidyr
dftest %>%
tidyr::replace_na(as.list(setNames(0, nacol)))
尝试dftest%>%group\u by(Id)%%>%mutate\u at(intersect(names(.),nacol),funs(replace(.,is.na(.))
@akrun,因为第一个参数(.vars)是作为字符向量(列名)给出的。不起作用的是使用带有列位置的数字向量。varsMakes sense,谢谢。是的,这里不需要group_by(分组依据)
,我简化了这个例子,但是如果我们有多行具有相同的id和funs(na.locf(,na.rm=F))
,例如,group_by
的使用将是明智的。@akrun我在重新学习如何指定列位置时遇到了这个问题。好消息+1.
dftest %>%
group_by(Id) %>%
mutate_at(intersect(names(.), nacol), funs(replace(., is.na(.), 0)))
dftest %>%
tidyr::replace_na(as.list(setNames(0, nacol)))