Home > Blockchain >  Wide to long format with multiple colums to one column
Wide to long format with multiple colums to one column

Time:09-22

dataframe <- data.frame(
  x1 = c("apple", "orange", "banana", "strawberry"),
  y = c("a", "d", "b", "c"),
  z = c(4:1), x2 = c("avocado", "kiwi", "fig", "grape"), 
  x3 = c("lime", "apple", "banana", "kiwi"))

Dear all, how to create this dataframe to long format in which all x1,x2 and x3 were merged as follows:

y x
a apple
a avocado
a lime
b orange
b kiwi
b apple

CodePudding user response:

library(tidyverse)

dataframe |> 
  select(-z) |> 
  pivot_longer(-y) |> 
  select(-name)
#> # A tibble: 12 × 2
#>    y     value     
#>    <chr> <chr>     
#>  1 a     apple     
#>  2 a     avocado   
#>  3 a     lime      
#>  4 d     orange    
#>  5 d     kiwi      
#>  6 d     apple     
#>  7 b     banana    
#>  8 b     fig       
#>  9 b     banana    
#> 10 c     strawberry
#> 11 c     grape     
#> 12 c     kiwi

CodePudding user response:

I'm not sure if the ys in your example are properly aligned but you can do this with a quick pivot

dataframe %>%
      pivot_longer(cols = contains("x"), values_to = 'x') %>%
      select(y, x)
  • Related