I'm trying to do some pre/post comparisons, a small sample below:
dataset =
data.table(
Key1 = c("p","q","r"),
Key2 = c("a","b","c"),
a_pre = c(3,2,6),
b_pre = c(2,6,3),
a_post = c(1,2,3),
b_post = c(1,4,2)
#etc.
)
dataset[,a_compare := a_pre/a_post]
dataset[,b_compare := b_pre/b_post]
#etc.
The problem is that the number of quantities I have is much more than just a and b, and is sometimes variable, so manually coding up each comparison is not an option. I'm trying to avoid eval(parse())
.
Assume that I have the names of the quantities c("a","b", etc.)
. My current thought process is along these lines:
loop through the quantity names
{
grep on colnames(dataset) for each quantity name,
use above to subset the pre and post column. include the keys in this subset.
send this subsetted dataset to a function that calculates pre/post irrespective of the specific quantity
merge result of function back to original dataset
}
I feel there must be a better way to do this. Any ideas?