【问题标题】:R: Same Function With Different Outputs When evaluate in dplyr::mutate()R:在 dplyr::mutate() 中评估时具有不同输出的相同功能
【发布时间】:2018-10-29 01:29:03
【问题描述】:

我是 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

我不明白为什么同一个函数会在 mutate 内部和外部评估不同的值。谁能解释一下?提前谢谢!

【问题讨论】:

  • 我假设birth 是一个等于“2-Jan-01”的字符串?这似乎是隐含的,但是我不知道您为什么需要将其转换为字符...您可以分享dput(birth) 的输出吗?

标签: r dplyr tidyverse


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 2013-07-16
    相关资源
    最近更新 更多