2

以下に小さなサンプルを示します。

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
}

これを行うためのより良い方法があるに違いないと感じています。何か案は?

4

3 に答える 3

2

forループは書きやすく読みやすいと思います:

basevars = c("a","b","c","d")
for (i in basevars)
    DT[, paste0(i,"_compare"):=get(paste0(i,"_pre"))/get(paste0(i,"_post"))]

+R が文字列で機能するように定義できなかった理由を、私は本当に知りませんでした。これは現在エラーであるため、使用されているようなものではありません。

> "a"+"b"
Error in "a" + "b" : non-numeric argument to binary operator

それ以外の場合は、次のように簡単に実行できます。

for (i in basevars)
    DT[, i+"_compare" := get(i+"_pre")/get(i+"_post")]
于 2013-09-26T17:31:20.630 に答える