【问题标题】:How do I reverse gather function in R?How do I reverse gather function in R?
【发布时间】:2022-12-27 04:20:04
【问题描述】:

I used gather function from tidyr to change the format of data wide to long. After that I removed NA values. How can I reverse this operation ?

first.df <- data.frame(a = c(1,NA,NA),b=c(2,3,NA),c=c(4,5,6)) 
second.df <- first.df %>% gather("x","y") %>% na.omit %>% `rownames<-`( NULL )

second.df: |x|y| |-|-| |a|1| |b|2| |b|3| |c|4| |c|5| |c|6|

How can I reverse this with spread or another function to first.df below ?

a b c
1 2 4
NA 3 5
NA NA 6

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    It requires a sequence column and then either dcast or pivot_wider can work or spread

    library(dplyr)
    library(tidyr)
    library(data.table)
    second.df %>% 
      mutate(rn = rowid(x)) %>% 
      pivot_wider(names_from = x, values_from = y) %>% 
      select(-rn)
    

    -output

    # A tibble: 3 × 3
          a     b     c
      <dbl> <dbl> <dbl>
    1     1     2     4
    2    NA     3     5
    3    NA    NA     6
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2022-12-01
      • 2022-12-01
      • 2022-12-01
      • 2022-12-01
      • 2022-12-27
      • 2022-11-09
      • 2022-12-27
      • 2022-12-27
      相关资源
      最近更新 更多