Home > Software engineering >  Using pivot wider in R
Using pivot wider in R

Time:11-25

I am having trouble converting a particular dataset from long to wide.

col1           col2
ID             55.
animal.        bear
shape.         circle
ID             67.
animal.        cat
shape.         square

I want it to look like

ID.   animal.  shape
55.    bear.   circle
67.    cat.    square

I'm sorry if this has already been answered I just can't seem to figure it out.

CodePudding user response:

We need to create a sequence by 'col1' before doing the pivot_wider

library(dplyr)
library(tidyr)
library(data.table)
df1 %>% 
   mutate(rn = rowid(col1)) %>% 
   pivot_wider(names_from = col1, values_from = col2) %>% 
   select(-rn) %>% 
   type.convert(as.is = TRUE)

-output

# A tibble: 2 × 3
     ID animal. shape.
  <dbl> <chr>   <chr> 
1    55 bear    circle
2    67 cat     square

data

df1 <- structure(list(col1 = c("ID", "animal.", "shape.", "ID", "animal.", 
"shape."), col2 = c("55.", "bear", "circle", "67.", "cat", "square"
)), class = "data.frame", row.names = c(NA, -6L))

CodePudding user response:

Yet another solution:

library(tidyverse)

df <- data.frame(
  stringsAsFactors = FALSE,
                    col1 = c("ID","animal.",
                             "shape.","ID","animal.","shape."),
              col2 = c("55.", "bear", "circle", "67.", "cat", "square")
      )

df %>% 
  pivot_wider(names_from = col1, values_from = col2, values_fn = list) %>% 
  unnest(cols = c(ID, animal., shape.))

#> # A tibble: 2 × 3
#>   ID    animal. shape.
#>   <chr> <chr>   <chr> 
#> 1 55.   bear    circle
#> 2 67.   cat     square
  •  Tags:  
  • r
  • Related