英文:
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)
}
输出将是:
<details>
<summary>英文:</summary>
use this:
X <- c("a", "b", "c", "d", "e")
for (letter in X[X != "d"]) {
print(letter)
}
output will be:
</details>
# 答案2
**得分**: 2
你可以使用以下代码来实现:
```R
setdiff(X, 'd')
或者
X[-grep('d', X)]
此外,R 中许多函数(如 print
)都是向量化的,因此它们会处理向量的所有元素,而不需要显式循环。
另外,对于许多情况,R 有更简洁、可读性更好、速度更快的替代循环的方式:整个 ...apply
系列,Map
,Reduce
(以及它们来自 {purrr} 的增强变体)等等。
你可以尝试 letters[1:5] |> setdiff('d') |> paste('is not d')
来看到管道操作符的魔力,也可以了解更多信息请查看 {purrr}。
英文:
You could use
setdiff(X, 'd')
or
X[-grep('d', 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] |> setdiff('d') |> paste('is not d')
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 == "d")]){
print(letter)
}
[1] "a"
[1] "b"
[1] "c"
[1] "e"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论