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

Convert the factors of a variable into the columns of the dataframe

I have a dataframe that looks like this

Concentration  Value
Low            0.21
Medium         0.85    
Low            0.10
Low            0.36
High           2.21
Medium         0.50
High           1.85

I would like to transform it into a dataframe where the column names are the factors of the variable:

Low      Medium    High
0.21     0.85      2.21
0.10     0.50      1.85
0.367 

I’ve tried using pivot_wider, however, the values for each of the factors are stored as vectors.

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

Low           Medium         High
c(0.21,...)   c(0.87 ,...)   c(1.47 ,...)

>Solution :

Use an id variable for rows by group:

dat %>% 
  group_by(Concentration) %>% 
  mutate(id = row_number()) %>% 
  pivot_wider(names_from = Concentration, values_from = Value)

     id   Low Medium  High
  <int> <dbl>  <dbl> <dbl>
1     1  0.21   0.85  2.21
2     2  0.1    0.5   1.85
3     3  0.36  NA    NA   
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