如何在 R 中转置时间序列数据,以便日期变量最终成为新变量名称

How to transpose times series data in R so that the date-variable ends up as the new variables names

我有一个庞大的时间序列数据集(超过 500 个变量),其中包含数年的月度观察。请参阅下面输入数据的简化示例(在 Excel 中):

现在,我需要做的(在 R 中)是转置这个输入数据集,以便变量日期作为新变量名称结束,而当前变量名称在日期列中结束。请参阅下面所需输出数据的简化示例(在 Excel 中):

请注意,所需最终结果中的变量名称中的日期必须按降序排列(最新最靠近左侧)。

我确实设法使用函数 t() 转置了数据,但是,问题随之而来。

  1. 第一个问题:变量date在转置后自动设置为rownames,这很好,我只是运行函数rownames_to_column()来解决这个问题。但是,有没有办法避免这种操作?

  2. 第二个问题:所有新变量名都在第一行结束,但是当我 运行 函数 row_to_names(1) 更改此日期时变量名最终变得很奇怪。我所做的唯一解决方案(几乎所有方法)是在 运行ning row_to_names(1) 之前首先将所有变量转换为字符格式。之后,我需要将我的日期变量改回数字格式,我需要这样做才能继续进行进一步的计算。但是,当我在我的真实数据集(相同但更大)上执行此操作时,我收到错误消息:“强制引入的 NA”。为什么会这样?我似乎无法找出原因。如果您找到其他方法也可以。

# Example data to copy and paste into R for easy reproduction of problem:

df <- data.frame (date  = c("2018-11-30", "2018-12-31", "2019-01-31", "2019-02-28", "2019-03-31", "2019-04-30"),
fruit_apples = c(333, 337, 341, 345, 349, 353),
fruit_pears = c(86, 87, 88, 89, 90, 91),
fruit_grapes    = c(255, 258, 261, 264, 267, 270),
veggies_tomatoes    = c(2024, 2025, 2026, 2027, 2028, 2029),
veggies_carrots = c(92, 95, 98, 101, 104, 107),
veggies_cucumber    = c(52, 54, 56, 58, 60, 62),
pets_rabbit = c(25, 26, 27, 28, 29, 30),
pets_cat    = c(51, 53, 55, 57, 59, 61),
pets_dog    = c(117, 121, 125, 129, 133, 137))

# The code I have been using so far:

df_output <- df %>%
  arrange(desc(date)) %>% # after transposing I want the newest date to be closest to the left, hence this step
  t() %>%
  as.data.frame() %>%
  rownames_to_column() %>%
  mutate(across(everything(), as.character)) %>%
  row_to_names(1) %>%
  mutate_at(vars(-date), as.numeric) %>% # causes error message "NAs introduced by coercion"
  adorn_totals()

我希望这是你的想法:

library(tidyr)

df %>%
  pivot_longer(!date, names_to = "Date", values_to = "value") %>%
  pivot_wider(names_from = date, values_from = value)

# A tibble: 9 x 7
  Date             `2018-11-30` `2018-12-31` `2019-01-31` `2019-02-28` `2019-03-31` `2019-04-30`
  <chr>                   <dbl>        <dbl>        <dbl>        <dbl>        <dbl>        <dbl>
1 fruit_apples              333          337          341          345          349          353
2 fruit_pears                86           87           88           89           90           91
3 fruit_grapes              255          258          261          264          267          270
4 veggies_tomatoes         2024         2025         2026         2027         2028         2029
5 veggies_carrots            92           95           98          101          104          107
6 veggies_cucumber           52           54           56           58           60           62
7 pets_rabbit                25           26           27           28           29           30
8 pets_cat                   51           53           55           57           59           61
9 pets_dog                  117          121          125          129          133          137

一个data.table方式-

library(data.table)

dcast(melt(setDT(df), id.vars = 'date'), variable~date, value.var = 'value')

#           variable 2018-11-30 2018-12-31 2019-01-31 2019-02-28 2019-03-31 2019-04-30
#1:     fruit_apples        333        337        341        345        349        353
#2:      fruit_pears         86         87         88         89         90         91
#3:     fruit_grapes        255        258        261        264        267        270
#4: veggies_tomatoes       2024       2025       2026       2027       2028       2029
#5:  veggies_carrots         92         95         98        101        104        107
#6: veggies_cucumber         52         54         56         58         60         62
#7:      pets_rabbit         25         26         27         28         29         30
#8:         pets_cat         51         53         55         57         59         61
#9:         pets_dog        117        121        125        129        133        137

我们可以使用 recast 来自 reshape2

library(reshape2)
 recast(df, id.var = 'date', variable ~ date)
          variable 2018-11-30 2018-12-31 2019-01-31 2019-02-28 2019-03-31 2019-04-30
1     fruit_apples        333        337        341        345        349        353
2      fruit_pears         86         87         88         89         90         91
3     fruit_grapes        255        258        261        264        267        270
4 veggies_tomatoes       2024       2025       2026       2027       2028       2029
5  veggies_carrots         92         95         98        101        104        107
6 veggies_cucumber         52         54         56         58         60         62
7      pets_rabbit         25         26         27         28         29         30
8         pets_cat         51         53         55         57         59         61
9         pets_dog        117        121        125        129        133        137