Home > database >  Convert the factors of a variable into the columns of the dataframe
Convert the factors of a variable into the columns of the dataframe

Time:04-11

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.

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

CodePudding user response:

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   
  •  Tags:  
  • r
  • Related