for R 中的循环迭代问题
for loop iterations issues in R
我正在尝试更加熟悉函数编写和 运行 一个我已经尝试解决了 3 个小时的问题。这是代码:
test <- function (x) {
for (i in x)
print(x[i])
}
当我分配几个变量时:
a <- c(0,1)
b <- c(1,2)
b 工作正常,但 'a' 搞砸了:
> test(b)
[1] 1
[1] 2
> test(a)
numeric(0)
[1] 0
我认为 R 在 'a' 中处理 1 和 0 的方式有问题。但是当我在命令行迭代函数时,没有问题。
print(a[1])
[1] 0
> print(a[2])
[1] 1
R 在函数内外如何区别对待命令?为什么 1 和 2 可以作为 'x',但 0 和 1 不行?
在你的函数中,
test <- function (x) {
for (i in x)
print(x[i]) ## you are print from the indexed value
}
因此在test(a)
您正在打印:
print(a[1]) # gives the first item in the vector a
print(a[2]) # gives the second item in the vector a
在test(b)
print(b[0]) # gives Null, since R is 1-based
print(b[1]) # gives the first item in the vector b
因此你得到了结果
如果要打印向量中的所有项目,可以将函数更改为
test <- function (x) {
for (i in 1:length(x))
print(x[i]) ## you are print from the indexed value
}
干杯,
生物鸟人
for 循环的语法将迭代 x
的 values 而不是 x
的 indices =].当您调用 test(c(0,1))
时,在 for
循环的第一次迭代中 i
的值为 0。这意味着您将尝试 print
第 0 个元素的论点。对于数字向量,在 R 中,这将始终给出 numeric(0)
,长度为 0 的数字变量的 R 项。对 R 有更好、更系统知识的人将不得不解释为什么这是一件好事,但是无论如何,这不是我认为你想要的。
a <- c(0,1)
b <- c(1,2)
> a[0]
numeric(0)
> b[0]
numeric(0)
我想你希望你的函数类似于
test2 <- function (x) {
for (i in 1:length(x))
print(x[i])
}
现在我们可以将您的函数 test
与 test2
进行比较,输入信息可能更丰富。
> test(c(101,202))
[1] NA
[1] NA
> test2(c(101,202))
[1] 101
[1] 202
或者我错过了您在最初问题中所追求的内容?
我正在尝试更加熟悉函数编写和 运行 一个我已经尝试解决了 3 个小时的问题。这是代码:
test <- function (x) {
for (i in x)
print(x[i])
}
当我分配几个变量时:
a <- c(0,1)
b <- c(1,2)
b 工作正常,但 'a' 搞砸了:
> test(b)
[1] 1
[1] 2
> test(a)
numeric(0)
[1] 0
我认为 R 在 'a' 中处理 1 和 0 的方式有问题。但是当我在命令行迭代函数时,没有问题。
print(a[1])
[1] 0
> print(a[2])
[1] 1
R 在函数内外如何区别对待命令?为什么 1 和 2 可以作为 'x',但 0 和 1 不行?
在你的函数中,
test <- function (x) {
for (i in x)
print(x[i]) ## you are print from the indexed value
}
因此在test(a)
您正在打印:
print(a[1]) # gives the first item in the vector a
print(a[2]) # gives the second item in the vector a
在test(b)
print(b[0]) # gives Null, since R is 1-based
print(b[1]) # gives the first item in the vector b
因此你得到了结果
如果要打印向量中的所有项目,可以将函数更改为
test <- function (x) {
for (i in 1:length(x))
print(x[i]) ## you are print from the indexed value
}
干杯, 生物鸟人
for 循环的语法将迭代 x
的 values 而不是 x
的 indices =].当您调用 test(c(0,1))
时,在 for
循环的第一次迭代中 i
的值为 0。这意味着您将尝试 print
第 0 个元素的论点。对于数字向量,在 R 中,这将始终给出 numeric(0)
,长度为 0 的数字变量的 R 项。对 R 有更好、更系统知识的人将不得不解释为什么这是一件好事,但是无论如何,这不是我认为你想要的。
a <- c(0,1)
b <- c(1,2)
> a[0]
numeric(0)
> b[0]
numeric(0)
我想你希望你的函数类似于
test2 <- function (x) {
for (i in 1:length(x))
print(x[i])
}
现在我们可以将您的函数 test
与 test2
进行比较,输入信息可能更丰富。
> test(c(101,202))
[1] NA
[1] NA
> test2(c(101,202))
[1] 101
[1] 202
或者我错过了您在最初问题中所追求的内容?