Search code examples
rcountdplyrstrsplit

R how to create columns/features based on existing data


I have a dataframe df:

userID Score  Task_Alpha Task_Beta Task_Charlie Task_Delta 
3108  -8.00   Easy       Easy      Easy         Easy    
3207   3.00   Hard       Easy      Match        Match
3350   5.78   Hard       Easy      Hard         Hard
3961   10.00  Easy       NA        Hard         Hard
4021   10.00  Easy       Easy      NA           Hard


1. userID is factor variable
2. Score is numeric
3. All the 'Task_' features are factor variables with possible values 'Hard', 'Easy', 'Match' or NA

I want to create new columns per userID that contain the counts of occurrence for each possible state of the Task_ feature. For the above toy example, the required output would be three new columns to be appended at the end of the df as below:

userID Hard Match Easy
3108   0    0     4
3207   1    2     1
3350   3    0     1
3961   2    0     1
4021   1    0     2

Update: This question is not a duplicate, an associated part of the original question has been moved to: R How to counting the factors in ordered sequence


Solution

  • You can compare the dataframe df to each value in a map* or *apply function, compute the row-wise sums of the resulting boolean matrix, then combine the output with the original dataframe:

    library(dplyr)
    library(purrr)
    
    facs <- c("Easy", "Match", "Hard")
    
    bind_cols(df, set_names(map_dfc(facs, ~ rowSums(df == ., na.rm = T)), facs))
    
    #### OUTPUT ####
    
      userID Score Task_Alpha Task_Beta Task_Charlie Task_Delta Easy Match Hard
    1   3108 -8.00       Easy      Easy         Easy       Easy    4     0    0
    2   3207  3.00       Hard      Easy        Match      Match    1     2    1
    3   3350  5.78       Hard      Easy         Hard       Hard    1     0    3
    4   3961 10.00       Easy      <NA>         Hard       Hard    1     0    2
    5   4021 10.00       Easy      Easy         <NA>       Hard    2     0    1