Home > Mobile >  How to sort these data in R
How to sort these data in R

Time:12-22

I am struggling to reshape the following data, especially creating headings

 df<-read.table (text="name IV  IM
    AZ  No  No
    AZ  No  Yes
    AZ  No  No
    AZ  No  Yes
    KL  No  No
    KL  Yes Yes
    KL  Yes Yes
    KL  No  No
", header=TRUE)

I want to get the following table

name    Iv1 Iv2 Iv3 Iv4 IM1 IM2 IM3 IM4
AZ      No  No  No  No  No  Yes No  Yes
KL      No  Yes Yes No  No  Yes Yes No

I have tried these codes, but I failed

reshape(df, idvar = "name", timevar = "IV", direction = "wide")

CodePudding user response:

You could tidyr's pivot_wider function:

library(tidyr)
library(dplyr)

df %>% 
  group_by(name) %>% 
  mutate(rn = row_number()) %>% 
  ungroup() %>% 
  pivot_wider(name, names_from = "rn", names_glue = "{.value}{rn}", values_from = c("IV", "IM"))

This returns

# A tibble: 2 x 9
  name  IV1   IV2   IV3   IV4   IM1   IM2   IM3   IM4  
  <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 AZ    No    No    No    No    No    Yes   No    Yes  
2 KL    No    Yes   Yes   No    No    Yes   Yes   No   
  • First we need to create a row number to get those indices for IV1, ..., IV4 and IM1, ..., IM4.
  • Then we use the row number combined with the value's column name to create the new "wide" shape containing the original values.
  • Related