使用Pivot_Longer()和Pivot_Wider(Tidyverse)转置Tibble

时间:2020-08-10 18:06:26

标签: r tidyverse

与此主题相关的类似问题全部使用了已退休的Tidyverse函数的spread()和collect()。假设我有这样的小标题:

people   1      2     3.    4     5
person1 27000 30000 40000 50000 60000
person2 27000 30000 40000 50000 60000
person3 27000 30000 40000 50000 60000
person4 27000 30000 40000 50000 60000

我想这样转置

People Person1 Person2 Person3 Person4 Person5
1.      270000  270000  270000. 270000. 270000
2.      30000.  30000. 30000  30000. 30000
3
4
5.     60000.   60000.  60000 60000 60000

(不是为了节省时间而填写第三和第四列,但应该将其填充。

1 个答案:

答案 0 :(得分:3)

使用data.table::transpose

更容易
library(data.table)
data.table::transpose(setDT(df1), make.names = 'people')[, People := .I][]

或使用tidyverse,可以分两步完成转置:1),使用pivot_longer重塑为长格式,2)使用pivot_wider重塑为另一列宽

library(dplyr)
library(tidyr)
df1 %>%
   pivot_longer(cols = -people, names_to = 'People') %>% 
   pivot_wider(names_from = people, values_from = value)
# A tibble: 5 x 5
#  People person1 person2 person3 person4
#  <chr>    <int>   <int>   <int>   <int>
#1 1        27000   27000   27000   27000
#2 2        30000   30000   30000   30000
#3 3        40000   40000   40000   40000
#4 4        50000   50000   50000   50000
#5 5        60000   60000   60000   60000

数据

df1 <- structure(list(people = c("person1", "person2", "person3", "person4"
), `1` = c(27000L, 27000L, 27000L, 27000L), `2` = c(30000L, 30000L, 
30000L, 30000L), `3` = c(40000L, 40000L, 40000L, 40000L), `4` = c(50000L, 
50000L, 50000L, 50000L), `5` = c(60000L, 60000L, 60000L, 60000L
)), class = "data.frame", row.names = c(NA, -4L))