I am trying to bind a table onto itself several times each time selecting a different column that will be dependent on where we are in the loop but I can't get it to work.
#create a test data.table
dt<-data.table(start=c(1,1,2,2,3,3,4,4),
start_2_end=0,
id=rep(c("A","B")),
ret1=1:8,
ret2=9:16,
ret3=17:24)
#Create table where start = end
cretdt <- dt[,.(start,
end=start,
id,
start_2_end=0,
cret=1)]
#loop and bind onto itself and pull in the correct ret column
for (i in 1:2)
{
cretdt <- rbind(cretdt,
dt[,.(start,
end=start+i,
id,
start_2_end=i,
cret=noquote(paste0("ret",(i+1)))
)]
)
}
My problem lies in the 'cret=noquote(paste0("ret",(i+1)))' portion; it just pulls in the name "ret2" and "ret3" instead of the corresponding value in the ret2 or ret3 column.
I have tried passing cret into a variable and then using eval() but that does not seem to work.
Is this possible to accomplish? Please help. Let me know if you need more details.
You're really looking for a reshape operation here, but I'll show another way of getting around the loop:
which gives
(Thanks @akrun for a simplification of the last term. I always forget about
mget
.)