I have an R data.table
like this:
id
1: 1
2: 29
3: 26
4: 6
5: 1
6: 14`
And I would like to add columns dynamically by presence of this Id in a row. Result:
id is_present_1 ... is_present_6....
1: 1 1 0
2: 2 0 0
3: 3 0 0
4: 4 0 1
5: 5 0 0
6: 6 0 1
I tried to write a function, or using mutate and paste:
ids <- c(1, 2, 3, 4, 5, 6)
for (i in length(ids)) {
df %>% mutate(paste("is_present",id[i]) = ifelse(id == ids[i],1,0))}
I get an error:
Error: unexpected '=' in: "for (i in length(ids)) { df %>% mutate(paste("is_present",id[i]) ="
Can someone help with this?