如何将 Dataframe 的一列转置为行,同时保持R中 Dataframe 的结构?[duplicate]

ruyhziif  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(166)
    • 此问题在此处已有答案**:

How to reshape data from long to wide format(14个答案)
Order columns in R based on numeric sequence(1个答案)
2天前关闭。
我有一个 Dataframe ,看起来像这样:

df <- data.frame(ID = c("A","A","A","A","A","B","B","B","B","B","C","C","C","C","C"),
                 code = c(1,2,2,3,3,1,2,2,1,1,3,2,2,1,1),
                 class =  c(2,4,5,5,2,3,2,5,1,2,4,5,3,2,1),
                 n = c(10,10,20,15,25,20,10,10,20,25,10,15,10,15,15))

我想把它转置一下,这样class列就变成了行,n就基于IDclassn展开,看起来就像这样:

|ID|class|1 |2 |3 |4 |5 |
|A |1    |  |10|  |  |  |
|A |2    |  |  |  |10|20|
|A |3    |  |25|  |  |15|
....
whitzsjs

whitzsjs1#

您可以使用pivot_widerarrange来获得列的数字顺序,如下所示:

library(dplyr)
library(tidyr)
df %>%
  arrange(class) %>%
  pivot_wider(names_from = class, values_from = n) %>%
  arrange(ID, code)
#> # A tibble: 8 × 7
#>   ID     code   `1`   `2`   `3`   `4`   `5`
#>   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 A         1    NA    10    NA    NA    NA
#> 2 A         2    NA    NA    NA    10    20
#> 3 A         3    NA    25    NA    NA    15
#> 4 B         1    20    25    20    NA    NA
#> 5 B         2    NA    10    NA    NA    10
#> 6 C         1    15    15    NA    NA    NA
#> 7 C         2    NA    NA    10    NA    15
#> 8 C         3    NA    NA    NA    10    NA

创建于2022年12月27日,使用reprex v2.0.2

相关问题