将数字 (%Y.%m) 列拆分为两列

时间:2021-04-13 14:36:56

标签: r

所以我有一个以下格式的时间序列:

<头>
日期(数字,%Y.%m) 价值
1951.01 12
1951.02 13

我正在尝试将日期列分成两列,如下所示:

<头>
价值
1951 01 12
1951 02 13

我尝试过使用 tidyr 中的 separator() 函数,效果还不错。但是,出于某种原因,它在第 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"))

4 个答案:

答案 0 :(得分:4)

已更新 由于我意识到您的 Date 列值是数字,因此我不想在不适合您的目的的状态下放弃我的代码。因此,您还可以使用以下解决方案来格式化 Date 列中的值,同时不会丢失月份值。

library(dplyr)
library(lubridate)


df %>%
  mutate(Date = format(Date, format = "%Y.%m.%d"), 
         Date = ym(Date), 
         Year = year(Date), 
         Month = month(Date)) %>%
  select(-Date) %>%
  relocate(-value)


# A tibble: 3 x 3
   Year Month value
  <dbl> <dbl> <dbl>
1  1951     1    12
2  1951     2    13
3  1951    10    14

使用@ThomasIsCoding 先生提出的数据来验证输出。

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"))

答案 1 :(得分:4)

如果 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"))

答案 2 :(得分:3)

先转换为 character,然后是 separate。如果你想要整数,只需添加 type.convert(as.is = TRUE)

library(dplyr)
library(tidyr)
df %>% 
  separate(`Date(numeric, %Y.%m)`, as.character(c("Year", "Month"))) %>% 
  type.convert(as.is = TRUE)

输出:

  Year  Month value
  <chr> <chr> <dbl>
1 1951  01       12
2 1951  02       13
###
# integer
   Year Month value
  <int> <int> <int>
1  1951     1    12
2  1951     2    13

答案 3 :(得分:1)

library(data.table)
dt <- data.table(date = c("1951.01","1951.02","1951.10"))
dt[,c("year","month") := tstrsplit(date,".",fixed = TRUE)]

#      date year month
#1: 1951.01 1951    01
#2: 1951.02 1951    02
#3: 1951.10 1951    10