Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I reverse gather function in R?

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading