0
我有一個包含行索引號的向量,我想根據這些數字創建一個新的虛擬變量,即向量中存在的行在新變量中的值爲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
}
下面是runnig最後三個命令時顯示的錯誤。
> 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
因此,在這裏我的目標是創建一個包含循環變量名稱的新「虛擬」變量和1
值分配給它其中行號碼get(paste0("matching.", x))$index.control
中的編號不一致。
使用'get()'和'assign()'通常表示你做錯了事(或者以非R的方式)。您可能應該使用命名列表來存儲元素,而不是創建一堆變量。最好從問題描述和期望的輸出開始,而不是專注於你如何嘗試去做。 – MrFlick
請舉例說明你想要什麼;如果你不得不每年測試一次,我會懷疑(你的例子)你會有index.control基於20個可能的值(但是限制每年)。作爲MrFlick highlitgjt,分配和獲取最多我不建議這樣做,我建議首先查看'split(df,df $ year)',它可以爲存儲的每年data.frame準備一個列表。 –