Home > Net >  How do I reverse gather function in R?
How do I reverse gather function in R?

Time:12-27

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

CodePudding user response:

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

Or with dcast

library(data.table)
dcast(second.df, rowid(x) ~ x, value.var = 'y')[,-1]
  • Related