首页 > 解决方案 > R:在 dplyr::mutate() 中评估时具有不同输出的相同功能

问题描述

我是 R 和 tidyverse 的新手。现在我遇到了一个问题:

假设我们有字符“2-Jan-01”:

运行函数时,我们得到:

as.Date("2-Jan-01", tryFormats = c("%y-%b-%d", "%b-%y-%d"))

[1] "2002-01-01"

但是,当我使用命令 mutate 时:

df %>%
mutate(birth_date=as.Date(as.character(birth),
tryFormats = c("%y-%b-%d", "%b-%y-%d")))

转换条目2-Jan-01时,我得到NA而不是2002-01-01.

我不明白为什么相同的函数会在变异内部和外部评估不同的值。谁能解释一下?先感谢您!

标签: rdplyrtidyverse

解决方案


你的代码对我来说运行良好。

librayr(dplyr)

df <- tibble(
  birth = "2-Jan-01"
)

保持您的代码不变:

df %>%
  mutate(birth_date = as.Date(
    as.character(birth),
    tryFormats = c("%y-%b-%d", "%b-%y-%d")
  ))

我得到:

  birth    birth_date
  <chr>    <date>    
1 2-Jan-01 2002-01-01

(请注意,我使用了 tibble,但它与传统数据框的工作方式相同)。

现在,没有理由as.character()在您的代码中使用,因为“birth”已经是类字符。所以删除它,我们有:

df %>%
  mutate(
    birth_date = as.Date(
      birth,
      tryFormats = c("%y-%b-%d", "%b-%y-%d")
    ))

这给出了相同的结果。

如果您不想保留旧的“出生”列,则可以transmute()改用:

df %>%
  transmute(
    birth_date = as.Date(
      birth,
      tryFormats = c("%y-%b-%d", "%b-%y-%d")
    ))

这使:

  birth_date
  <date>    
1 2002-01-01

推荐阅读