【问题标题】:Transposition of a Tibble Using Pivot_Longer() and Pivot_Wider (Tidyverse) [duplicate]使用 Pivot_Longer() 和 Pivot_Wider (Tidyverse) 对 Tibble 进行转置 [重复]
【发布时间】:2020-08-10 18:06:26
【问题描述】:

关于这个主题的类似问题都使用了已退休的 Tidyverse 函数的 spread() 和 gather()。假设我有一个这样的小标题:

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

(没有填写第三和第四列只是为了节省自己的时间,但它们应该已经填写了。

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

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

    【讨论】:

    • 谢谢,但我实际上知道这个问题的解决方案。我只是想看看一个整洁的诗歌方式。还是点赞了你的帖子。 :)
    • 刚刚看到您的新编辑.. 谢谢!如果允许,我会在 9 分钟内接受您的回答!
    • @Steveman30290 谢谢,我使用了transpose,因为它更直接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多