To calculate some aggregates of x over label and add it to data I could use following code, for mean it is :
library(data.table)
setDT(data)[, y := mean(x), label]
but how to calculate means only when size of group given by label is over 5 and input 0 otherwise. I was first trying to calculate size of groups using length,nrow instead of mean keyword, but it is not the right way and doesn't work. Sample dataset I work with :
set.seed(123)
data<-data.frame(label=sample(c("A","B"),10,replace=TRUE),x=rnorm(10))
data
# label x
#1 A 1.7150650
#2 B 0.4609162
#3 A -1.2650612
#4 B -0.6868529
#5 B -0.4456620
#6 A 1.2240818
#7 B 0.3598138
#8 B 0.4007715
#9 B 0.1106827
#10 A -0.5558411
I see that trying code like :
setDT(data)[, y := ifelse(nrow(x)>10,mean(x),0), label] # don't run
is wrong direction.
I'd suggest you avoid ifesle all together both because efficiency and because it's just wrong to put 0 when you don't want to calculate the mean, what will happen if one of the groups also will have a zero mean, how would you distinguish between them? I'd just do
setDT(data)[, y := mean(x)[.N > 4] , label][]
# label x y
# 1: A 1.7150650 NA
# 2: B 0.4609162 0.03327823
# 3: A -1.2650612 NA
# 4: B -0.6868529 0.03327823
# 5: B -0.4456620 0.03327823
# 6: A 1.2240818 NA
# 7: B 0.3598138 0.03327823
# 8: B 0.4007715 0.03327823
# 9: B 0.1106827 0.03327823
# 10: A -0.5558411 NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With