我正在尝试做一些前后比较,下面是一个小样本:
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.
问题是我拥有的数量不仅仅是 a 和 b,而且有时是可变的,因此手动编码每个比较不是一种选择。我试图避免eval(parse())
。
假设我有数量的名称c("a","b", etc.)
。我目前的思考过程是这样的:
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
}
我觉得必须有更好的方法来做到这一点。有任何想法吗?