在迭代字符向量时跳过某些元素时出错。

huangapple go评论71阅读模式
英文:

Error when iterating over a character vector but omitting some elements

问题

我对R语言非常陌生,遇到了一些在遍历字符向量时的问题。

当遍历数值向量时,使用否定运算符'-'来省略其中一个元素相对容易。例如:

for (i in (1:5)[-4]){
  print(i)
}

会输出:

[1] 1
[1] 2
[1] 3
[1] 5

然而,将相同的方法应用于字符向量会引发错误:

X = c("a", "b", "c", "d", "e")
for (letter in (X)[-"d"]){
  print(letter)
}

Error in -"d" : invalid argument to unary operator

我尝试了多种变体,但似乎都返回相同的错误。我想知道为什么这两种情况会被不同对待,以及正确的语法是什么?

英文:

I'm very new to R and am having some trouble when iterating through a character vector.

When iterating through a numeric vector, it is rather easy to omit one of the elements using the negation operator '-'. For example

for (i in (1:5)[-4]){
  print(i)
}

yields

[1] 1
[1] 2
[1] 3
[1] 5

However, applying the same method to a character vector raises an error

X = c("a", "b", "c", "d", "e")
for (letter in (X)[-"d"]){
  print(letter)
}

Error in -"d" : invalid argument to unary operator

I have tried multiple variations on the above but all seem to return the same error. I was wondering if someone could tell me why these two cases are treated differently and what the correct syntax is?

答案1

得分: 2

使用此代码:

X <- c("a", "b", "c", "d", "e")
for (letter in X[X != "d"]) {
print(letter)
}

输出将是:

1 "a"
1 "b"
1 "c"
1 "e"


<details>
<summary>英文:</summary>

use this:

X <- c("a", "b", "c", "d", "e")
for (letter in X[X != "d"]) {
print(letter)
}

output will be:

1 "a"
1 "b"
1 "c"
1 "e"


</details>



# 答案2
**得分**: 2

你可以使用以下代码来实现:

```R
setdiff(X, 'd')

或者

X[-grep('d', X)]

此外,R 中许多函数(如 print)都是向量化的,因此它们会处理向量的所有元素,而不需要显式循环。

另外,对于许多情况,R 有更简洁、可读性更好、速度更快的替代循环的方式:整个 ...apply 系列,MapReduce(以及它们来自 {purrr} 的增强变体)等等。

你可以尝试 letters[1:5] |> setdiff('d') |> paste('is not d') 来看到管道操作符的魔力,也可以了解更多信息请查看 {purrr}。

英文:

You could use

setdiff(X, &#39;d&#39;)

or

X[-grep(&#39;d&#39;, X)]

Aside 1: many functions in R (like print) are vectorised, so they will digest all elements of a vector without explicitly being told to loop anyway.

Aside 2: R has more concise/readable/faster equivalents to loops in many cases: the whole ...apply family, Map, Reduce (and their steroid variants from {purrr}) and such.

Try letters[1:5] |&gt; setdiff(&#39;d&#39;) |&gt; paste(&#39;is not d&#39;) to watch the pipe operator doing its magic, too 在迭代字符向量时跳过某些元素时出错。

答案3

得分: 1

为了在[中使用-,我们需要使用数字索引。因此,我们需要使用which来找出X中“d”的位置。

for (letter in X[-which(X == "d")]){
  print(letter)
}

[1] "a"
[1] "b"
[1] "c"
[1] "e"
英文:

To use - in [, we need numeric indices. So we need to find out the position of "d" in X by using which.

for (letter in X[-which(X == &quot;d&quot;)]){
  print(letter)
}

[1] &quot;a&quot;
[1] &quot;b&quot;
[1] &quot;c&quot;
[1] &quot;e&quot;

huangapple
  • 本文由 发表于 2023年6月22日 19:50:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定