首页 文章

使用group_by时mutate_at评估错误

提问于
浏览
3

mutate_at()显示与group_by()一起使用时以及将列位置的数字向量作为第一个(.vars)参数进行插入时的评估错误 .

  • 使用 R 3.4.2和 dplyr 0.7.4版本时出现问题

  • 使用 R 3.3.2和 dplyr 0.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, 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,.)))

Error in mutate_impl(.data, dots) : 
Evaluation error: object 'NA' not found.

更明智的例子证明问题:

# 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)))

1 回答

  • 3

    我们得到NA值的原因是我们从 which 获得的输出是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
    

    这里不需要 group_by ,因为我们正在将其他列中的NA值更改为0

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

    这可能是一个错误,使用基于位置的方法有时是有风险的 . 更好的选择是使用 names

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

    注意:在所有这些情况下,不需要 group_by


    另一种选择是来自 tidyrreplace_na

    dftest %>%
        tidyr::replace_na(as.list(setNames(0, nacol)))
    

相关问题