所以我有一个具有以下格式的时间序列:
日期(数字,%Y.%m)
值(value)
1951.01
12
1951.02
13
我试图将日期列分成两列,如下所示:
年
月
值(value)
1951年
01
12
1951年
02
13
我试过使用 tidyr 的 separate() 函数,它有点工作。但是,出于某种原因,它在第 10 个月删除了 0,如下所示:
data$month
... 8 9 1 11 ...
我怀疑这与将其强制为字符(?)有关。我试过使用 substr() 但它也不起作用,同样的问题。有没有更好的方法来做到这一点?我的代码:
data %>%
separate(Date, into = c("year","month"))
** 编辑我认为这绝对是因为我将数字日期强制转换为字符。
as.character(1951.10)
[1] "1951.1"
可重现的样本数据:df <- structure(list(Date = c(1951.01, 1951.02, 1951.1),
value = c(12,13, 14)), row.names = c(NA, -3L),
class = c("tbl_df", "tbl","data.frame"))
最佳答案
如果 Date
列中有数值,则应首先将其转换为 character
并保留两位小数。在这里你可以使用 sprintf
来制作它。然后你用 .
分割字符串。
试试下面的代码
df %>%
mutate(Date = sprintf("%.2f", Date)) %>%
separate(Date, c("Year", "Month"), "\\.")
这使 Year Month value
<chr> <chr> <dbl>
1 1951 01 12
2 1951 02 13
3 1951 10 14
数据 > dput(df)
structure(list(Date = c(1951.01, 1951.02, 1951.1), value = c(12,
13, 14)), row.names = c(NA, -3L), class = c("tbl_df", "tbl",
"data.frame"))
关于r - 将数字 (%Y.%m) 列拆分为两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67076960/