I have example data as follows:
library(data.table)
sample <- fread("
1,0,2,NA,cat X, type 1
3,4,3,1,cat X, type 2
1,0,2,2,cat X, type 3
3,4,3,0,cat X, type 4
1,0,2,NA,cat Y, type 1
3,4,3,NA,cat Y, type 2
1,0,2,2,cat Y, type 3
3,4,3,35,cat Y, type 4
1,0,2,NA,cat X, type 1
3,4,3,1,cat X, type 2
1,0,2,2,cat X, type 3
3,4,3,NA,cat X, type 4
1,0,2,NA,cat Y, type 1
3,4,3,NA,cat Y, type 2
1,0,2,2,cat Y, type 3
3,4,3,1,cat Y, type 4
1,0,2,4,cat X, type 1
3,4,3,1,cat X, type 2
1,0,2,2,cat X, type 3
3,4,3,2,cat X, type 4
1,0,2,NA,cat Y, type 1
3,4,3,NA,cat Y, type 2
1,0,2,2,cat Y, type 3
3,4,3,2,cat Y, type 4
")
names(sample) <- c("A","B","C", "D", "cat", "type")
sample <- sample[, observations := sum(!is.na(D)), by = c("cat", "type")]
A B C D cat type observations
1: 1 0 2 NA cat X type 1 1
2: 3 4 3 1 cat X type 2 3
3: 1 0 2 2 cat X type 3 3
4: 3 4 3 0 cat X type 4 2
5: 1 0 2 NA cat Y type 1 0
6: 3 4 3 NA cat Y type 2 0
7: 1 0 2 2 cat Y type 3 3
8: 3 4 3 35 cat Y type 4 3
9: 1 0 2 NA cat X type 1 1
10: 3 4 3 1 cat X type 2 3
...
24: 3 4 3 0 cat Y type 4 3
I would like to add the neighbouring group type
s together if they have fewer than two observations.
For example: add the group of type 1
with only 1 observation to the observations in group 2 (see the first line of the desired output).
Types need to be pooled together until all remaining categories have at least 2 observations. So type 1
and type 2
of category Y
, need to be pooled with type 3
.
I am having trouble coming up with way of writing code for this.
Can anyone suggest a good way to automatically create the new types?
I realise that there might be situations in which there might be two possible solutions for pooling the groups. However, as long as the groups which are added together are neighbouring groups (so type 1
is not added to type 4
, which groups are added together are not important.
Desired output:
A B C D cat type new_type observations
1: 1 0 2 NA cat X type 1 type 2 4
2: 3 4 3 1 cat X type 2 type 2 4
3: 1 0 2 2 cat X type 3 type 3 3
4: 3 4 3 0 cat X type 4 type 4 2
5: 1 0 2 2 cat Y type 1 type 3 3
6: 3 4 3 NA cat Y type 2 type 3 3
7: 1 0 2 2 cat Y type 3 type 3 3
8: 3 4 3 0 cat Y type 4 type 4 3
9: 1 0 2 NA cat X type 1 type 2 4
10: 3 4 3 1 cat X type 2 type 2 4
...
24: 3 4 3 0 cat Y type 4 type 4 3
Solution does NOT have to use data.table