包括一个列表组件,并在 R 中重复排除所有其他组件



我有一个值列表。我想在函数的一部分中使用第一个值,并在函数的单独部分中使用剩余的值。然后,我想在函数的一部分中使用列表中的第二个值,并在函数的另一部分中使用剩余的值(包括第一个值(。

以下不是真正的代码,因为我已经排除了一些函数输入,但它显示了我正在尝试执行的操作:

group <- c(1, 3, 4, 5, 9) #the complete group 
#It is important to note that these values are not continuous. They are distinct values. 

#include 1st unit of the list group as treatment and then use
#the remaining values as controls 
controls_not2 <- c(3, 4, 5, 9)
df1 <- dataprep(treatment = 1, controls = controls_not1) 
gaps.plot(dataprep = df1) 

#use the 2nd unit from the list as the treatment and use
#the remaining values as controls 
controls_not2 <- c(1, 4, 5, 9)
df2 <- dataprep(treatment = 3, controls = controls_not3) 
gaps.plot(dataprep = df3) 

在完整列表中,我有大约 50 个值。有没有办法让我按照上面显示的方式迭代所有这些值?


以下是一些其他信息。

使用的软件包:

library(tidyverse) 
library(synth) 

下面是创建单个图形的完整代码的示例。

treatment.identifier 等效于我在上面简单示例中的治疗。 controls.identifier 等效于我在上面示例中作为控件所拥有的控件。

dataprep.out1 <- dataprep(foo = as.data.frame(df), 
predictors = predictors1, 
predictors.op = "mean", 
special.predictors = NULL, 
dependent = "logfatalitiespercapita", 
unit.variable = "state", 
time.variable = "year", 
treatment.identifier = "99", 
controls.identifier = controlstates, 
time.predictors.prior = c(1981:1985), 
time.optimize.ssr = c(1981:1985), #check on these years
time.plot = 1981:2003, 
unit.names.variable = "statenames") 
#identifying weights that create the best possible synthetic control unit for the treated 
synth.out1 <- synth(dataprep.out1)
#graph
spec1 <- gaps.plot(dataprep.res = dataprep.out1, synth.res = synth.out1, Xlab = c("Year"), Ylab = c("Gap"))

要将结果存储在列表中,这将忽略值是什么并使用 1:50 作为索引

library(purrr)
result <- map(1:50, ~{ #replace 50 with the length of your list
df <- dataprep(treatment = group[[.x]], controls = group[[-.x]])
gaps.plot(dataprep = df)})

这是一个受上述解决方案启发的类似解决方案。

newfunction <- function(x) {
df <- dataprep(treatment = group[x], controls = group[-x])
gaps.plot(dataprep = df)
}
graphs <- lapply(group, newfunction) 

首先是注释,您可能不想使用"list"作为向量名称,因为list是R中的数据类型。您可以通过引用索引号来子集向量。下面是示例。

列表1 <- C(1, 3, 4, 5, 9( #the 完整组

df1 <- dataprep(treatment = 1, controls = list1[c(1,3:length(list1))]) 
gaps.plot(dataprep = df1) 

#use the 2nd unit from the list as the treatment and use
#the remaining values as controls 
df2 <- dataprep(treatment = 3, controls = list1[c(2)]) 
gaps.plot(dataprep = df3) 
library(tidyverse)
myVec = 1:6
doSomething <- function(treatment, myVec){
controls = myVec[! myVec == treatment]
paste("Treatment:", treatment, "Controls:", paste(controls, collapse = "-"))
}
map_chr(myVec, ~ doSomething(.x, myVec))
[1] "Treatment: 1 Controls: 2-3-4-5-6" "Treatment: 2 Controls: 1-3-4-5-6" "Treatment: 3 Controls: 1-2-4-5-6"
[4] "Treatment: 4 Controls: 1-2-3-5-6" "Treatment: 5 Controls: 1-2-3-4-6" "Treatment: 6 Controls: 1-2-3-4-5"

最新更新