私は行のインデックス番号を含むベクトルを持っているので、それらの数値に基づいて新しいダミー変数を作成したいと思います。つまり、ベクトルに存在する行は新しい変数に1の値を持ちます。私はこれをループで試行しています。ループ変数の値を格納するには、新しい変数名が必要です。問題は、変数が存在しない限りその変数に値を代入することができないということですが、作成することもできません。名前に変数名を含む新しい列を作成する方法(ループ内)?
以下は、いくつかの疑似データとコマンドの例です。
set.seed(100)
df <- data.frame(id = 1:20,
year = sample(2011:2013, 20, replace = TRUE),
dum = sample(0:1, 20, rep = TRUE),
var = sample(10:99, 20))
for (x in 2011:2013) {
# Below I take a subset of data to test models for different years.
assign(paste0("subset.", x), df[df$year == x, ])
# Here I would test a model.
# Below I imitate matching of propensity scores and create an object that contains
# row indexes of control group.
set.seed(x)
assign(paste0("matching.", x), list(data = df, index.control = sample(1:20, 4)))
# Below I attempt to take the row indexes ofcontrol goup from the created 'matching' object and create
# a new dummy variable that determines the control group. None of the commands work.
assign(get(paste0("subset.", x))[get(paste0("matching.", x))$index.control, paste0("control.", x)], 1)
get(paste0("subset.", x))[get(paste0("matching.", x))$index.control, paste0("control.", x)] <- 1
get(paste0("subset.", x))[[get(paste0("matching.", x))$index.control, paste0("control.", x)]] <- 1
}
以下は最後の3つのコマンドを実行したときに表示されるエラーです。
> assign(get(paste0("subset.", x))[get(paste0("matching.", x))$index.control, paste0("control.", x)], 1)
Error in assign(get(paste0("subset.", x))[get(paste0("matching.", x))$index.control, :
invalid first argument
> get(paste0("subset.", x))[get(paste0("matching.", x))$index.control, paste0("control.", x)] <- 1
Error in get(paste0("subset.", x))[get(paste0("matching.", x))$index.control, :
target of assignment expands to non-language object
> get(paste0("subset.", x))[[get(paste0("matching.", x))$index.control, paste0("control.", x)]] <- 1
Error in get(paste0("subset.", x))[[get(paste0("matching.", x))$index.control, :
target of assignment expands to non-language object
したがって、ここでの私の目標は、ループ変数名を含む新しい「ダミー」変数を作成し、行番号がget(paste0("matching.", x))$index.control
に番号と一致どこに1
の値を割り当てることです。
'get()'と 'assign()'は通常、間違っている(または非常にRに似ていない)ことを示す記号です。変数の束を作成するのではなく、名前付きリストを使用して要素を格納する必要があります。どのようにしてやったかに焦点を当てるのではなく、問題の説明と望ましい出力から始めておく方がよいでしょう。 – MrFlick
あなたが望むものの例を示してください。あなたが年にテストしなければならない場合、実行される分割があり、20の可能な値に基づいてindex.controlを持つことは疑いの余地があります(ただし、1年あたりの制限を設けます)。MrFlick highlitgjtとして、ケースは大歓迎ではありません。最初に、毎年のdata.frameが格納されたリストを作成する 'split(df、df $ year)'を見てみましょう。 –