I have this data frame:
Generacion 1 2 3 4 5 6 NP1 NP2 NP3 NP4 NP5 NP6
1: 1 0 0 0 0 0 0 4 4 4 4 5 5
2: 2 0 0 0 0 0 0 4 4 4 4 4 4
3: 3 0 0 0 0 0 0 5 5 5 5 5 5
4: 4 0 0 0 0 0 0 4 5 5 5 4 4
5: 5 0 0 0 0 0 0 5 4 4 4 4 4
6: 6 0 0 0 0 0 0 5 5 5 5 4 4
I want to modify columns 1 through 6 such that each column counts the occurrences of that value in the the right columns (NP1 - NP6). That is, the 4 column should count the number of times 4 occurs. I wish to repeat this process with every number. The number that can take values between 0 and 5. The final result should be like this:
head(t2 %>% select(1, 2, 3, 4, 5, 6, 7, NP1, NP2, NP3, NP4, NP5, NP6))
Generacion 1 2 3 4 5 6 NP1 NP2 NP3 NP4 NP5 NP6
1: 1 0 0 0 4 2 0 4 4 4 4 5 5
2: 2 0 0 0 6 0 0 4 4 4 4 4 4
3: 3 0 0 0 0 6 0 5 5 5 5 5 5
4: 4 0 0 0 3 3 0 4 5 5 5 4 4
5: 5 0 0 0 5 1 0 5 4 4 4 4 4
6: 6 0 0 0 2 4 0 5 5 5 5 4 4
I have tried using the package data.table, I have done the following:
t2[NP1 == 4]$`4` <- t2[NP1 == 4]$`4` + 1
But I had the following error:
Error in
[<-.data.table(*tmp*, NP1 == 4, value = c(1, 1, 1, 1)) : Can't assign to the same column twice in the same query (duplicates detected).
So I have 2 questions:
- Why do I get this error?
- Is there an easier, more intuitive way to do it?