Search code examples
rdataframeunique

Add new columns to data frame for each unique value in another column


I'd like to add a new column for each unique value in another column. Then for each of these columns the value will either be the value from the other column, or zero.

For the example below i would like to add 4 new columns (A:D), for column B would be (0,0,0,0,5,6,7,8,0,0,0,0,0,0,0,0) etc.

df <- data.frame(Group=rep(c('A', 'B', 'C', 'D'), each=4),
                 score=1:16)        
df

Solution

  • Using map_dfc:

    library(purrr)
    library(dplyr)
    map_dfc(setNames(unique(df$Group), unique(df$Group)), 
            ~ ifelse(df$Group == .x, df$score, 0)) %>% 
      bind_cols(df, .)
    
       Group score A B  C  D
    1      A     1 1 0  0  0
    2      A     2 2 0  0  0
    3      A     3 3 0  0  0
    4      A     4 4 0  0  0
    5      B     5 0 5  0  0
    6      B     6 0 6  0  0
    7      B     7 0 7  0  0
    8      B     8 0 8  0  0
    9      C     9 0 0  9  0
    10     C    10 0 0 10  0
    11     C    11 0 0 11  0
    12     C    12 0 0 12  0
    13     D    13 0 0  0 13
    14     D    14 0 0  0 14
    15     D    15 0 0  0 15
    16     D    16 0 0  0 16
    

    Or in base R:

    cbind(df, 
          sapply(unique(df$Group), \(x) ifelse(df$Group == x, df$score, 0)))