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 to sort these data in R

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

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

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

>Solution :

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.
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