id <- c(1:8,1:8)
age1 <- c(7.5,6.7,8.6,9.5,8.7,6.3,9,5)
age2 <- age1 + round(runif(1,1,3),1)
age <- c(age1, age2)
tanner <- sample(1:2, 16,replace=T)
d
We can use dcast
to convert from 'long' to 'wide' and use the fun.aggregate
as min
. Here I converted the 'data.frame' to 'data.table' (setDT(df)
) as the dcast
from data.table
would be fast.
library(data.table)
res <- dcast(setDT(df), id~paste('age',tanner,sep='.'), value.var='age', min)
res
# id age.1 age.2
#1: 1 10.0 7.5
#2: 2 6.7 Inf
#3: 3 11.1 8.6
#4: 4 Inf 9.5
#5: 5 8.7 11.2
#6: 6 6.3 8.8
#7: 7 9.0 Inf
#8: 8 5.0 Inf
If we want to change the 'Inf' to 'NA'
res[,(2:3) := lapply(.SD, function(x)
replace(x, is.infinite(x), NA)),.SDcols= 2:3]