r 中具有多个条件的 For 循环返回相同的值

For loop with multiple conditions in r returning same values

我创建了一些具有逻辑值 true 和 false 的向量,我想使用 for 循环来识别所有具有 "TRUE" 值的向量。

"Master"、"master" 和 "MSc" 都是 1:45 向量,我想使用多个 "or" 条件来定义所有 "TRUE" 值,将创建一个新向量,取值 "Master":

 n <- nrow(fs)
 for (i in 1:n) {
   if(Master[i]=="TRUE"||master[i]=="TRUE"||MSc[i]=="TRUE"){
     fs$data.linkedin_education_degree1[i] <- "Master"
   }
 }

虽然 "Master"、"master" 和 "MSc" 看起来像:

> Master
 [1]  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE   FALSE  TRUE FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE
[24] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE
> master
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[24] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
> MSc
 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[24] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE

在运行这个循环之后,我想我会得到一些"Master"和"NA",但实际上所有的返回值都是"Master"?!

> fs$data.linkedin_education_degree1
 [1] "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master"
[16] "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master"
[31] "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master" "Master"

我似乎找不到循环中的错误。有人可以提供帮助吗?非常感谢!


Paul Hiemstra 编辑:

以下示例代码无法重现您的问题。您能否通过使用我的示例代码重现问题或为上述代码提供数据来使问题重现:

m1 = c(TRUE, TRUE, FALSE)
m2 = c(TRUE, FALSE, FALSE)
m3 = c(TRUE, TRUE, FALSE)
result = rep(NA, 3)

n <- length(m1)
for (i in 1:n) {
  if (m1[i] == 'TRUE' || m2[i] == 'TRUE') {
    result[i] = 'Master'
  }
}
# > result
# [1] "Master" "Master" NA

您提供的示例无法重现您面临的问题...

无论如何,正如@Paul Hiemstra 在评论中建议的那样,您可以在没有循环的情况下完成它,如下所示:

fs$data.linkedin_education_degree1 <- ifelse(Master | master | Msc, 'Master', NA)