【问题标题】:dplyr conditional mutate on itselfdplyr 对自身进行条件变异
【发布时间】:2016-11-08 18:11:53
【问题描述】:

我有一个数据框,其中的字符变量主要由数值组成,偶尔还有一些已知字符串以及一些 NA 值。我想有条件地将数值重新格式化为小数点后一位,但不考虑字符和 NA 值。

此代码适用于玩具数据框并产生所需的输出:

df <- data.frame(a = c("1", "2", "3", "none", NA),
                 stringsAsFactors = FALSE)

test <- df %>%
  mutate(a = ifelse(is.na(a) | a == "none",
                    a,
                    format(round(as.numeric(a), 1), nsmall = 1)))

test
#    a
# 1  1.0
# 2  2.0
# 3  3.0
# 4 none
# 5 <NA>

但会引发警告消息

Warning message:
In format(round(as.numeric(c("1", "2", "3", "none", NA)), 1), nsmall = 1) :
  NAs introduced by coercion

我相信这种情况 b/c format(round(as.numeric(a), 1), nsmall = 1))) 仍然作用于整个向量,即使其中的值仅用于 mutate 语句中 ifelse 条件为假。

我可以将整个内容包装在suppressWarnings() 中,但是有没有其他方法可以在dplyr 框架内生成所需的输出而不会发出警告?我敢肯定有一个data.table 的方法可以做到这一点,但这是一个不需要data.table 的包的一部分,对于这么小的一块来说它似乎很愚蠢......

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    使用replace,可以只转换a列中的数值类型数据:

    test <- df %>%
        mutate(a = replace(a, !is.na(a) & a != "none",
                           format(round(as.numeric(a[!is.na(a) & a != "none"]), 1), nsmall = 1)))
    
    test
    #     a
    #1  1.0
    #2  2.0
    #3  3.0
    #4 none
    #5 <NA>
    

    【讨论】:

      猜你喜欢
      • 2014-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 2017-06-02
      相关资源
      最近更新 更多