启动数据框
data_start <- data.frame(marker = c("yes","yes","no","yes","no"),
id_out = c(5,3,1,1,7),
id_new = c(6,8,9,4,2))
> data_start
marker id_out id_new
1 yes 5 6
2 yes 3 8
3 no 1 9
4 yes 1 4
5 no 7 2
在下方添加三列标题,空列。附加起始var1:var3
值。
data_start[,c("var1", "var2", "var3")] <- NA
vars <- c(5,3,1)
data_start[1, 4:6] <- vars
> data_start
marker id_out id_new var1 var2 var3
1 yes 5 6 5 3 1
2 yes 3 8 NA NA NA
3 no 1 9 NA NA NA
4 yes 1 4 NA NA NA
5 no 7 2 NA NA NA
我想通过将函数应用于IF var1:var3
= marker
和yes
与id_out
中的任何一行匹配的每一行来更新我的var1:var3
列,将var1:var3
替换为id_new
。我找到了这个解决方案,但适用于一行代码,仍然需要更新行的每个新var1:var3
部分。
data_start[1, 4:6][data_start[1, 4:6] == data_start[1,"id_out"]] <- data_start[1,"id_new"]
在再次应用函数之前,每行还依赖于使用上一行中的值。
最终输出看起来像这样,当标记= no
并且随后更新每行时,行保持不变。
> data_final
marker id_out id_new var1 var2 var3
1 yes 5 6 6 3 1
2 yes 3 8 6 8 1
3 no 1 9 6 8 1
4 yes 1 4 6 8 4
5 no 7 2 6 8 4
答案 0 :(得分:1)
这可以与任意数量的列一起使用,并与基数R一起使用:
cols <- c("var1", "var2", "var3")
for(j in 1:length(cols)) {
var <- cols[j]
for(i in 1:nrow(data_start)){
if(i > 1) {
data_start[i, var] <- data_start[i-1, var]
}
if(data_start[i, "marker"] == "yes" & data_start[i, var] == data_start[i,"id_out"]) {
data_start[i,var] <- data_start[i, "id_new"]
}
}
}
答案 1 :(得分:0)
由于我必须运行,因此非常粗暴地将它放在一起,但这应该可行。
data_start <- data.frame(marker = c("yes","yes","no","yes","no"),
id_out = c(5,3,1,1,7),
id_new = c(6,8,9,4,2))
data_start[,c("var1", "var2", "var3")] <- NA
vars <- c(5,3,1)
data_start[1, 4:6] <- vars
onVars <- c("var1", "var2", "var3")
for (i in 2:nrow(data_start)) {
print(i)
for (var in onVars) {
if (data_start$marker[i] == "yes" & data_start$id_out[i] == data_start[i - 1, var]) {
data_start[i, var] <- data_start$id_new[i]
} else {
data_start[i, var] <- data_start[i - 1, var]
}
}
}
data_start是你的输出。
哎呀,看起来我可能已经遗漏了对第一行的评价,但希望你现在可以自己处理。
答案 2 :(得分:0)
以下是一个代码段,即使您有三列以上,也可以进行此计算:
library(data.table)
dt <- data.table(marker = c("yes","yes","no","yes","no"),
id_out = c(5,3,1,1,7),
id_new = c(6,8,9,4,2))
dt[, change := cumsum(marker == "yes")]
ref.new <- dt[marker == "yes", id_new] # Reference to values where marker is "yes"
ref.out <- dt[marker == "yes", id_out]
for (x in 1:length(ref.new)) {
dt[, paste("var", x, sep="") := ifelse(change >= x, ref.new[x] , ref.out[x])]
}
head(dt)
# marker id_out id_new change var1 var2 var3
#1: yes 5 6 1 6 3 1
#2: yes 3 8 2 6 8 1
#3: no 1 9 2 6 8 1
#4: yes 1 4 3 6 8 4
#5: no 7 2 3 6 8 4
答案 3 :(得分:0)
似乎很难找到没有for循环的解决方案,如果,那么就是这样。我尝试使用其他设置更改原始值,例如c(1,3,1)
,代码工作正常。如果需要,我们还可以添加更多变量列。
# Re-create the data
dt <- data.table(marker = c("yes","yes","no","yes","no"),
id_out = c(5,3,1,1,7),
id_new = c(6,8,9,4,2))
var.col <- paste0("var", 1:3)
dt[1, (var.col) := .(5,3,1)]
# Processing
for(i in 1:nrow(dt)) {
if(i > 1) dt[i, (var.col) := as.list(dt[i-1, var.col, with = F])]
var.i <- dt[i, var.col, with = F] %in% dt[i, id_out]
if(dt[i]$marker == 'yes' & sum(var.i) != 0) {
dt[i, (var.col[var.i]) := dt[i, id_new]]
}
}