从年(双精度)和周数(字符)构造年周

时间:2020-03-17 12:51:56

标签: r tsibble

这是我的数据样本

# A tibble: 300 x 5
    year week  department_id media_tpv mediana_tpv
   <dbl> <chr>         <dbl>     <dbl>       <dbl>
 1  2019 00                3      90.4         65 
 2  2019 00                5     194.         117.
 3  2019 00               65     173.         117.
 4  2019 00               93     183.         105 

现在,说我想从中构造一个基于tsibble::yearweek()的索引。我尝试一起粘贴年份和星期,然后将其传递给yearweek(),但无法正确解析。

dput:

df <- structure(list(year = c(2019, 2019, 2019, 2019), week = c("00", 
"00", "00", "00"), department_id = c(3, 5, 65, 93), media_tpv = c(90.4, 
194, 173, 183), mediana_tpv = c(65, 117, 117, 105)), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))

1 个答案:

答案 0 :(得分:1)

您只需要将两列强制转换为yearweek所需要的格式:

df$week <- paste0('W', df$week)
df$yearweek <- paste0(df$year, ' ', df$week)
yearweek_column <- yearweek(df$yearweek)

然后您可以检查:

print(yearweek)

哪个给您:

[1] "2018 W52" "2018 W52" "2018 W52" "2018 W52"

tidyverse解决方案:

df %>%
  mutate(week = paste0('W', week),
         yearweek = paste0(year, ' ', week),
         yearweek_column = yearweek(yearweek))