R语言学习笔记——for循环

基本语法:for (i in ()){} 或 for (i in 1:n){}

例一、为向量赋值

x <- rnorm(5) #随机生成5个均值为0,标准差为1的数
y <- numeric(length(x)) #产生长度为length(x)的数值型向量
for(i in 1:5){
  if(x[i]>=0){
    y[i] <- 8}else{
      y [i] <- 7}
}
print(y)
[1] 7 7 7 8 7

x <- 0
y <- 0
#seq(1:n):生成一个连续序列
for(i in seq(1:5)){
  x <- 2*x+3
  y <- y+x
}
y
[1] 171 

例二、构造矩阵并赋值

a <- matrix(0,5,5) #构造一个全为0的5×5矩阵
for(i in 1:5){
  for (j in 1:5){
    a[i,j] = (i+j)
}
  }
a
     [,1] [,2] [,3] [,4] [,5]
[1,]    2    3    4    5    6
[2,]    3    4    5    6    7
[3,]    4    5    6    7    8
[4,]    5    6    7    8    9
[5,]    6    7    8    9   10

a <- matrix(0,5,5) #构造一个全为0的5×5矩阵
b <- c(1:25) 
c <- 1
for (m in 1:5){
  for (n in 1:5){
    a[m,n] = b[c] #按行赋值
    #a[n,m] = b[c] 按列赋值
    c <- c+1 
}
  }
a
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    6    7    8    9   10
[3,]   11   12   13   14   15
[4,]   16   17   18   19   20
[5,]   21   22   23   24   25

你可能感兴趣的:(r语言,学习)