具有等级的 Dataframe 到具有有序列表的 Dataframe

piah890a  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(123)

我有这个数据框架,其中列出了引用排名的每一个品种由三个人:

variety <- c("variety1","variety2","variety3","variety4","variety5")
people1 <- c(1, NA, 3, 2, NA)
people2 <- c(4, 3, 2, 1, NA)
people3 <- c(3, 2, 5, 4, 1)
df <- data.frame(variety, people1, people2, people3); df

我想要一个列表或 Dataframe ,如下所示:

people1 <- c("variety1", "variety3", "variety4",NA,NA)
people2 <- c("variety4", "variety3", "variety2", "variety1", NA)
people3 <- c("variety5", "variety2", "variety1", "variety4", "variety3")
df2 <- data.frame(people1, people2, people3); df2

所以每一列都代表一个人(people),并且按照输入df中给出的顺序(rank)列出了品种名称。
谢谢你,

umuewwlo

umuewwlo1#

函数pivot_widerpivot_longer对于重构数据非常有用。

library(tidyverse)

df %>% 
    pivot_longer(
        cols = people1:people3,
        names_to = 'person',
        values_to = 'rank'
    ) %>% 
    filter(!is.na(rank)) %>% 
    pivot_wider(
        id_cols = rank,
        names_from = 'person', 
        values_from = 'variety'
    ) %>% 
    arrange(rank)

# A tibble: 5 × 4
   rank people1  people2  people3 
  <dbl> <chr>    <chr>    <chr>   
1     1 variety1 variety4 variety5
2     2 variety4 variety3 variety2
3     3 variety3 variety2 variety1
4     4 NA       variety1 variety4
5     5 NA       NA       variety3

相关问题