欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

R语言for循环①

程序员文章站 2024-02-03 11:16:58
...
  • for循环是一种重复控制结构,可以让您有效地编写一个需要执行特定次数的循环。

for (value in vector) {
   statements
}

示例:


j <- LETTERS[1:4]
for ( i in j) {
   print(i)
}

它产生如下结果:

[1] "A"
[1] "B"
[1] "C"
[1] "D"

下标访问

> a <- c("a","b","c","d")
> for (i in c(1:length(a)))
+ {print(i)}

[1] 1
[1] 2
[1] 3
[1] 4

元素访问

> a <- c("a","b","c","d")
> for (i in c(1:length(a)))
+ {print(a[i])}

[1] "a"
[1] "b"
[1] "c"
[1] "d"

循环嵌套

> a <- matrix(c(1:50),nrow=5)
> a
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    6   11   16   21   26   31   36   41    46
[2,]    2    7   12   17   22   27   32   37   42    47
[3,]    3    8   13   18   23   28   33   38   43    48
[4,]    4    9   14   19   24   29   34   39   44    49
[5,]    5   10   15   20   25   30   35   40   45    50
> for (i in c(1:nrow(a)))
+   for (j in c(1:ncol(a)))
+   {print(a[i,j])}
[1] 1
[1] 6
[1] 11
[1] 16
[1] 21
[1] 26
[1] 31
[1] 36
[1] 41
[1] 46
[1] 2
[1] 7
[1] 12
[1] 17
[1] 22
[1] 27
[1] 32
......
......