我有一个具有以下形式的离散值增加的向量:
a<-c(1,2,5,7,8,9,10,15,19...)
我想运行一个遍历 a 的值的 for 循环。
我试过了:
for (i in 1:a)
但这忽略了缺少值,并且还会查看 3、4 等。
我也试过:
for (i in 1:unique(a))
但这会产生以下错误:
In 1:unique(a) :
numerical expression has 1350 elements: only the first used
我有一个具有以下形式的离散值增加的向量:
a<-c(1,2,5,7,8,9,10,15,19...)
我想运行一个遍历 a 的值的 for 循环。
我试过了:
for (i in 1:a)
但这忽略了缺少值,并且还会查看 3、4 等。
我也试过:
for (i in 1:unique(a))
但这会产生以下错误:
In 1:unique(a) :
numerical expression has 1350 elements: only the first used
试试这个:
for ( i in a )
a已经是一个向量。1:N您通常在循环中看到的构造for用作创建从 1 到 N 的整数向量的简写形式。
蒂姆指出了解决这个问题的正确方法。但是,根据您所做的尝试,您可能还想查看?seq并查看?seq_along
1:a 并且1:unique(a)都取向量中的第一个元素a(或unique(a))并将其用作序列中的“上限”。(只要 的第一个元素a可以强制转换为整数)。
例如
a <- c("7", "hello", "world")
1:a # same as 1:7
# [1] 1 2 3 4 5 6 7
a <- c("hello", "7", "world")
1:a # same as 1:"hello"
# ERROR
如果您使用seq_along(a),它将为您提供 a 的每个元素的索引。(如果您需要将该索引用于其他计算,则很有用)
for (i in seq_along(a))
cat(a[[i]], "\t is the", i,"element.\n")
# hello is the 1 element.
# 7 is the 2 element.
# world is the 3 element.