[英]For loop with discrete values in R
我有一個向量增加以下形式的離散值:
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
已經是一個向量。 您通常在for
循環中看到的1:N
構造用作創建從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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.