r - 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
.
我不明白为什么相同的函数会在变异内部和外部评估不同的值。谁能解释一下?先感谢您!
解决方案
你的代码对我来说运行良好。
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
推荐阅读
- javascript - Javascript 中的 Prettier 将变量定义强制到下一行
- javascript - 再次单击选中的单选按钮时,我需要触发 onChange 事件
- sql - 用联合连接子查询(一个表有两个条件)
- android - 使用 FrameLayout 创建 DialogFragment
- microsoft-graph-api - 就地存档邮件的父 ID 错误
- ssl - 树莓派上不支持 SSL 的协议
- postgresql - PostgreSQL - 如何在另一列上添加具有默认条件的新列?
- gatsby - gatsby-source-cloudinary:如何将视频和图像都添加到资源类型标签中?
- html - 如何摆脱 SVG 占用的空间以及为什么无法更改其大小?
- javascript - Mongoose Pagination - 在第一次查询时限制为 1,然后在后续查询中限制为 10