【发布时间】:2021-07-26 04:11:40
【问题描述】:
我有一个 csv,其中包含“Period”,即季度和“Percent”。将数据读入 R 后,“Period”列为“chr”,“Percent”列为“num”。我想将季度值更改为日期,所以:
for (i in 1:length(sloos_tighten$Period)) {
sloos_tighten$Period[i] <- paste("Q", substring(sloos_tighten$Period[i], 6), "/", substring(sloos_tighten$Period[i], 1, 4), sep = "")
sloos_tighten$Period[i] <- as.Date(as.yearqtr(sloos_tighten$Period[i], format = "Q%q/%Y"))
}
for 循环中的第一行将季度的格式更改为 as.yearqtr 可读,第二行将季度更改为日期。第一行按预期工作,但第二行将日期转换为四位数。我认为这是因为“Period”属于“chr”类型,但我不知道如何将其更改为最新。我试图创建一个类型为 date 的新列,但我在网上找不到任何解释它的资源。任何帮助表示赞赏。提前致谢。
> dput(head(sloos_tighten, 10))
structure(list(Period = c("1990:2", "1990:3", "1990:4", "1991:1",
"1991:2", "1991:3", "1991:4", "1992:1", "1992:2", "1992:3"),
`Large and medium` = c(54.4, 46.7, 54.2, 38.6, 20, 18.6,
16.7, 10, 3.5, -3.4), Small = c(52.7, 33.9, 40.7, 31.6, 6.9,
8.8, 7, 0, -7.1, -1.7)), row.names = c(NA, 10L), class = "data.frame")
^导入后数据的样子
【问题讨论】:
-
欢迎栈溢出;请使用
dput(sloos_tighten)或dput(head(sloos_tighten, 10))将数据样本粘贴到问题中,以使您的问题可重复minimal reproducible example