我正在尝试找出一种快速旋转该表的方法。我的输入表是这样的
+------+------+------+
| FY | col1 | col2 |
+------+------+------+
| 2019 | 34 | 28 |
+------+------+------+
| 2018 | 22 | 39 |
+------+------+------+
我希望输出表为
+-----------+-----------+-----------+-----------+
| col1.2018 | col1.2019 | col2.2018 | col2.2018 |
+-----------+-----------+-----------+-----------+
| 22 | 34 | 39 | 28 |
+-----------+-----------+-----------+-----------+
最快捷的方法是什么?我尝试使用reshape和tidyr,但没有得到所需的输出。任何指导或指导表示赞赏
编辑:正如所指出的,这并非与其他问题完全相同。虽然相似,但不一样
答案 0 :(得分:-1)
一个选择是将gather
列('col1','col2')设为gather
的长格式,unite
将'key'设为'FY'列,然后spread
恢复为“宽”格式
library(tidyverse)
gather(df1, key, val, col1:col2) %>%
unite(key1, key, FY, sep=".") %>%
spread(key1, val)
# col1.2018 col1.2019 col2.2018 col2.2019
#1 22 34 39 28
df1 <- structure(list(FY = c(2019, 2018), col1 = c(34, 22), col2 = c(28,
39)), class = "data.frame", row.names = c(NA, -2L))