R使用mutate转换EncounterDate_G为年-月-日格式报错如何解决
错误原因
across()的第二个参数要求传入函数对象、公式或函数列表,你编写的mdy()会直接执行函数,没有传入待处理的列作为参数,因此触发参数类型不匹配的报错。
修正方案
你的EncounterDate_G列原始格式为月/日/年,使用lubridate的mdy函数完全可以正常解析,正确写法如下:
library(dplyr) library(lubridate) gwlfullflattened22 <- gwlfullflattened2 %>% # 单列转换不需要用across,直接操作即可 mutate(EncounterDate_G = mdy(EncounterDate_G)) %>% # 若需要输出"年-月-日"格式的字符串而非日期类型,可放开下行注释 # mutate(EncounterDate_G = format(EncounterDate_G, "%Y-%m-%d")) %>% as_tibble()
如果你需要同时处理多列日期,across的正确写法为传入不带括号的函数名:
# 示例:同时转换EncounterDate_G和date_of_birth_G两列日期 gwlfullflattened22 <- gwlfullflattened2 %>% mutate(across(c(EncounterDate_G, date_of_birth_G), mdy)) %>% as_tibble()
转换后EncounterDate_G的日期类型默认打印即为年-月-日格式,完全符合需求。
内容的提问来源于stack exchange,提问作者Ash S
相关产品推荐
相关产品推荐

