是否可以分开日期?
所以就像“YYYYMMDD”就像“20170831”一样。
如何将“20150101”转换为“2015-01-01”,谢谢。
A <- data.frame(Item_A = c("00EF", "00EF", "00EF", "00EF", "00EF", "00FR",
"00FR"),Item_B = c("JAMES RIVER", "JAMES RIVER", "JAMES RIVER",
"JAMES RIVER", "JAMES RIVER", "RICE MIDSTREAM", "RICE
MIDSTREAM"),
DATE = c("20150101", "20150102", "20150103", "20150104",
"20150105", "20150106", "20150107"))
EXPECT:
A <- data.frame(Item_A = c("00EF", "00EF", "00EF", "00EF", "00EF", "00FR",
"00FR"),Item_B = c("JAMES RIVER", "JAMES RIVER", "JAMES RIVER",
"JAMES RIVER", "JAMES RIVER", "RICE MIDSTREAM", "RICE
MIDSTREAM"),
DATE = c("2015-01-01", "2015-01-02", "2015-01-03", "2015-01-
04","2015-01-05", "2015-01-06", "2015-01-07"))
答案 0 :(得分:2)
我们可以使用tidyverse
library(tidyverse)
A %>%
mutate(DATE = ymd(DATE))
答案 1 :(得分:1)
我们可以使用anytime
A$DATE <- anytime::anytime(A$DATE)
(无需加载整个宇宙)
如果A
是一个大型数据框,我们可以使用data.table
library(data.table)
setDT(A)[, DATE := as.IDate(DATE, "%Y%m%d")][]
更新到位,即不复制整个数据对象以保护内存和时间。
注意两种方法都将DATE
列转换为类Date
。 OP给出的预期结果显示DATE
为字符串。因此,如果OP真的希望字符串作为输出DATE
需要使用format(A$DATE)
进行第二次转换,例如