我有一個嵌套回圈,使用它進入一組 if 陳述句。當我的 id 列是連續的 (1:6) 時,代碼運行良好。當我將 id 列內容更改為亂數(1、5、9、11、15、21)時,代碼不再起作用,并且重復出現錯誤“if (data$death[i] < data$data[ j]) { : 需要 TRUE/FALSE 的缺失值”。
這是新資料框的示例以及用于設定向量然后運行嵌套回圈和 if 陳述句的代碼。如果 id 編號是連續的 1:6,則沒有錯誤。但是當 id 更改為以下時,錯誤不斷出現。誰能建議為什么會發生此錯誤以及有關如何避免它的任何建議?非常感謝!
id|intervention|death
1|2|0
5|2|1
9|2|0
11|1|1
15|1|0
21|1|0
test <- c()
for (i in data$id[which(data$intervention == 1)]) {
for(j in data$id[which(data$intervention == 2)]){
if (data$death[i] < data$death[j]){
test <- c(test,-1)}
else if (data$death[i] > data$death[j]){
test <- c(test,1)}
else if(data$death[i]==data$death[j]){
test <- c(test,0)}
}
test
}
uj5u.com熱心網友回復:
可能有更簡單的方法來實作您的目標。這是代碼的一種修復。
data <- data.frame(
id = c(1, 5, 6, 11, 15, 21),
intervention = c(2, 2, 2, 1, 1, 1),
death = c(0, 1, 0, 1, 0, 0)
)
test <- c()
for (i in data$id[which(data$intervention == 1)]) {
print(paste0("id = ", i, ": "))
for (j in data$id[which(data$intervention == 2)]) {
if (data$death[data$id == i] < data$death[data$id == j]) {
test <- c(test, -1)
} else if (data$death[data$id == i] > data$death[data$id == j]) {
test <- c(test, 1)
} else if (data$death[data$id == i] == data$death[data$id == j]) {
test <- c(test, 0)
}
}
print(test)
test <- c()
}
[1] "id = 11: "
[1] 1 0 1
[1] "id = 15: "
[1] 0 -1 0
[1] "id = 21: "
[1] 0 -1 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529476.html
上一篇:MongoDBif引數中的陳述句
