Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

data.table: calculation condition on presence of value within group

$
0
0

With some data

library(data.table); set.seed(42)
dat <- data.table(id=1:5, group=c(1,1,1,2,2), time=c(1,2,3,1,2), val=runif(5))
> dat
   id group time       val
1:  1     1    1 0.9148060
2:  2     1    2 0.9370754
3:  3     1    3 0.2861395
4:  4     2    1 0.8304476
5:  5     2    2 0.6417455

and I would like to apply some calculation, say val*2, to time point 2 only to those groups for which there is no third time point.

I suspected it is something along the lines of

dat[,val:=val[max(time)==2]*2, by=group]

but this would not work. Because I want to apply the calculation to a different time point than the one I am subsetting on, I felt this can't be done in i but I would not know how to do it instead.


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>