我正在尝试运行以下循环
for(i in 1:5) {
nam <- paste("cons_", i, sep = "")
new_data[nam] <- with(new_data, ifelse(cons>2 & remember==1 & comp==i, 1, NA))
new_data[nam] <- with(new_data, ifelse(cons<3 & remember==1 & comp==i, 0, new_data[nam]))
}
new_data [nam]&lt; - with(new_data,ifelse(cons2&lt; 3&amp; aided == 1&amp; brand == i ,0, new_data [nam] ))
粗体的 SECOND 部分是我遇到麻烦的地方,因为我想要一些现有的数据(真正的NA)不被覆盖。我以为我可以只分配变量名称,但它没有正确评估它。有更好的方法吗?
以下是dput
数据的head
(有更好的方法可以做到这一点)。我们的想法是,有几个人为comp
(它是一个堆叠数据集)提供评级。我注意到我试过的循环实际上只是填充了第一个变量,如果我将它嵌套。
structure(
list(
id = 1:6,
comp = c(1L, 1L, 1L, 1L, 1L, 1L),
remember = c(1L,
1L, 1L, 1L, 1L, 1L),
cons2 = c(3L,
1L, 1L, 2L, 2L, 3L),
cons_1 = c(1, 0, 0, 0, 0, 1),
cons_2 = c(NA,
NA, NA, NA, NA, NA),
cons_3 = c(NA, NA, NA, NA, NA, NA),
cons_4 = c(NA,
NA, NA, NA, NA, NA),
cons_5 = c(NA, NA, NA, NA, NA, NA),
cons_6 = c(NA,
NA, NA, NA, NA, NA),
cons_7 = c(NA, NA, NA, NA, NA, NA),
cons_9 = c(NA,
NA, NA, NA, NA, NA)
),
.Names = c(
"id",
"comp",
"remember",
"cons2",
"cons_1",
"cons_2",
"cons_3",
"cons_4",
"cons_5",
"cons_6",
"cons_7",
"cons_9"
),
row.names = c(NA, 6L),
class = "data.frame"
)