In the example df, I want to move the "group" variable with 5 levels to 5 different variables, and determine which group they belong in. (I know it's kind of weird formatting, but that's easier for future calculation and analysis)
Example df:
|x |group |date |
|1 |1 |2021-01-01 |
|1 |1 |2021-01-02 |
|1 |1 |2021-01-03 |
|1 |2 |2021-01-10 |
|1 |2 |2021-01-11 |
|1 |3 |2021-01-20 |
|1 |3 |2021-01-21 |
|1 |3 |2021-01-22 |
|1 |4 |2021-02-22 |
|1 |5 |2021-03-22 |
Expected result:
|x |date |group1 |group2 |group3 |group4 |group5 |
|1 |2021-01-01 |TRUE |FALSE |FALSE |FALSE |FALSE |
|1 |2021-01-02 |TRUE |FALSE |FALSE |FALSE |FALSE |
|1 |2021-01-03 |TRUE |FALSE |FALSE |FALSE |FALSE |
|1 |2021-01-10 |FALSE |TRUE |FALSE |FALSE |FALSE |
|1 |2021-01-11 |FALSE |TRUE |FALSE |FALSE |FALSE |
|1 |2021-01-20 |FALSE |FALSE |TRUE |FALSE |FALSE |
|1 |2021-01-21 |FALSE |FALSE |TRUE |FALSE |FALSE |
|1 |2021-01-22 |FALSE |FALSE |TRUE |FALSE |FALSE |
|1 |2021-02-22 |FALSE |FALSE |FALSE |TRUE |FALSE |
|1 |2021-03-22 |FALSE |FALSE |FALSE |FALSE |TRUE |
I've tried pivot_wider, but I don't know where should be the values from. And I've also tried the following codes:
df = df %>%
mutate(group1= 0,
group2= 0,
group3= 0,
group4= 0,
group5= 0) %>%
for (i in 1:nrow(df)){
if(group == 1){group1 = TRUE}
else if(group == 2){group2 = TRUE}
else if(group == 3){group3 = TRUE}
else if(group == 3){group4 = TRUE}
else {group5 = TRUE}
}
And the error is: Error in for (. in i) 1:nrow(df) :4 arguments passed to 'for' which requires 3