在R中,将列“Date”中的字符串模式替换为正确的格式。

huangapple go评论59阅读模式
英文:

Replace string pattern in Column Date with the correct format in R

问题

在我的数据框中,日期列的格式不标准。我想将所有"x1Q2013"更改为"2013-01-01","x2Q2013"更改为"2013-04-01",以此类推,直到"X1Q2023"更改为"2023-01-01"。

谢谢!

gsub可以删除前面的部分,但如何添加后面的部分并保留年份呢?

英文:

Under my data frame, the Date column only is not in the standard format. I want to change anything that say x1Q2013 to 2013-01-01 x2Q2013 to 2013-04-01 so forth until X1Q2023 to 2023-01-01

Thank you!

gsub can remove the front part, but how to add the back part and keep the year.

答案1

得分: 1

使用 zoo 可以将季度年份转换为日期:

library(zoo)
dates = c("x1Q2013", "x2Q2013")
as.Date(as.yearqtr(dates, format = "x%qQ%Y"))
#[1] "2013-01-01" "2013-04-01"
英文:

With zoo you can convert quarter year to dates:

library(zoo)
dates = c("x1Q2013", "x2Q2013")
as.Date(as.yearqtr(dates, format = "x%qQ%Y"))
#[1] "2013-01-01" "2013-04-01"

huangapple
  • 本文由 发表于 2023年5月25日 05:07:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定