问题描述
我有一个数据框,其中包含多个日期值作为字符串的列(格式:YYYYMMDD)。
dt_example <- data.frame (
W03 = "20201130",W44 = "19711031",P01 = "19740813",P04 = "20000506",Z02 = "20201231"
)
现在我想将字符串转换为日期格式并尝试了以下工作正常的代码:
dt_example_date <- dt_example %>%
mutate(
W03 = as.Date(W03,"%Y%m%d"),W44 = as.Date(W44,P01 = as.Date(P01,P04 = as.Date(P04,Z02 = as.Date(Z02,"%Y%m%d")
)
但是这段代码很烦人,我想使用“mutate cross”而不是多个 as.Date-conversions。
我尝试了几种替代方法,但没有任何效果。
dt_example_date_2 <- dt_example %>%
mutate(
across(
c("W03","W44","P01","P04","Z02"),as.Date
)
)
结果:字符串不是标准的明确格式
dt_example_date_2 <- dt_example %>%
mutate(
across(
c("W03",as.Date(format="%y%m%d")
)
)
结果:缺少参数“x”
dt_example_date_2 <- dt_example %>%
mutate(
across(
c("W03",as.Date(.,format="%y%m%d")
)
)
结果:不知道如何转换'.'对“日期”进行分类
我没听懂,也不知道该怎么办。
如何将参数传递给跨命令中使用的函数?
您好 贝恩
解决方法
试试这个:
#Code
dt_example_date_2 <- dt_example %>%
mutate(
across(
c(W03,W44,P01,P04,Z02),~as.Date(.,format="%Y%m%d")
)
)
输出:
dt_example_date_2
W03 W44 P01 P04 Z02
1 2020-11-30 1971-10-31 1974-08-13 2000-05-06 2020-12-31
为避免输入所有名称,您可以尝试此操作(非常感谢并感谢 @latlio):
#Code 2
dt_example_date_2 <- dt_example %>%
mutate(
across(
everything(),format="%Y%m%d")
)
)
相同的输出。
,a) 您需要以逗号分隔的形式传递格式参数。
b) 您的格式有错别字(小写“y”而不是大写)。
dt_example %>%
mutate(across(c("W03","W44","P01","P04","Z02"),as.Date,format = "%Y%m%d"))
给出:
W03 W44 P01 P04 Z02
1 2020-11-30 1971-10-31 1974-08-13 2000-05-06 2020-12-31
,
Base R 解决方案:如果您之前将其转换为矩阵,则可以简单地将结构直接传递给 as.Date。
dt_example_date <- as.Date(as.matrix(dt_example),"%Y%m%d")
# [1] "2020-11-30" "1971-10-31" "1974-08-13" "2000-05-06" "2020-12-31"
str(dt_example_date)
# Date[1:5],format: "2020-11-30" "1971-10-31" "1974-08-13" "2000-05-06" "2020-12-31"
或保留数据帧结构:
as.data.frame(sapply(X = dt_example,FUN = as.Date,"%Y%m%d",simplify = F))
# W03 W44 P01 P04 Z02
#1 2020-11-30 1971-10-31 1974-08-13 2000-05-06 2020-12-31
,
你可以像下面这样用across
试试everything()
> dt_example %>%
+ mutate(across(everything(),format = "%Y%m%d"))
W03 W44 P01 P04 Z02
1 2020-11-30 1971-10-31 1974-08-13 2000-05-06 2020-12-31
data.table
选项是
> setDT(dt_example)[,lapply(.SD,format = "%Y%m%d")]
W03 W44 P01 P04 Z02
1: 2020-11-30 1971-10-31 1974-08-13 2000-05-06 2020-12-31
使用 list2DF
+ Map
的基本 R 选项
> list2DF(Map(as.Date,dt_example,"%Y%m%d"))
W03 W44 P01 P04 Z02
1 2020-11-30 1971-10-31 1974-08-13 2000-05-06 2020-12-31
,
您可以使用 lubridate 包:
data.frame (
W03 = "20201130",W44 = "19711031",P01 = "19740813",P04 = "20000506",Z02 = "20201231"
) %>%
mutate(across(everything(),lubridate::ymd))
这给出:
W03 W44 P01 P04 Z02
1 2020-11-30 1971-10-31 1974-08-13 2000-05-06 2020-12-31