R中循环中的"if-clause"中的字符串比较导致"条件长度> 1且仅使用第一个元素"?

yos*_*ian 5 if-statement r string-comparison

我对R中的这种行为感到困惑.我只是想对strsplit生成的字符串列表进行简单的字符串比较.所以不明白为什么下面的前两个代码片符合我的预期,而第三个不是.

> for (i in strsplit("A text I want to display with spaces", " ")) { print(i) }
[1] "A"       "text"    "I"       "want"    "to"      "display" "with"    "spaces" 
Run Code Online (Sandbox Code Playgroud)

好的,这很有道理......

> for (i in strsplit("A text I want to display with spaces", " ")) { print(i=="want") }
[1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)

好的,这也是.但是,以下结构有什么问题?

> for (i in strsplit("A text I want to display with spaces", " ")) { if (i=="want")     print("yes") }
Warning message:
In if (i == "want") print("yes") :
  the condition has length > 1 and only the first element will be used
Run Code Online (Sandbox Code Playgroud)

当遇到第四个单词时,为什么不打印"是"?我应该改变什么以达到这个理想的行为?

Ben*_*ker 7

问题是strsplit产生一个拆分字符串列表(在这种情况下长度为1,因为你只给它一个字符串来拆分).

ss <- strsplit("A text I want to display with spaces", " ")
for (i in ss[[1]]) {
  if (i=="want")     print("yes")
}
Run Code Online (Sandbox Code Playgroud)

如果您只是打印元素,您可以看到发生了什么:

for (i in ss) {
  print(i)
}
Run Code Online (Sandbox Code Playgroud)

第一个元素是character向量.

根据您正在做的事情,您也可以考虑矢量化比较,例如 ifelse(ss=="want","yes","no")