楚新元 | All in R

Welcome to R Square

R 语言基础编程

楚新元 / 2021-08-17


以下主要摘录《R 语言编程艺术》和《R 语言实战》其中一些 R 语言编程的经典入门实例。

向量 for 循环

# 计算 x^2
x = c(1, 2, 3)
for (i in x) {
  print(i^2)
}
#> [1] 1
#> [1] 4
#> [1] 9
# 九九乘法表
for (j in 1:9) {
  for(i in 1:j){
    m = i * j
    cat(i,'*',j,'=',m,' ')
  }
  cat('\n')
}
#> 1 * 1 = 1  
#> 1 * 2 = 2  2 * 2 = 4  
#> 1 * 3 = 3  2 * 3 = 6  3 * 3 = 9  
#> 1 * 4 = 4  2 * 4 = 8  3 * 4 = 12  4 * 4 = 16  
#> 1 * 5 = 5  2 * 5 = 10  3 * 5 = 15  4 * 5 = 20  5 * 5 = 25  
#> 1 * 6 = 6  2 * 6 = 12  3 * 6 = 18  4 * 6 = 24  5 * 6 = 30  6 * 6 = 36  
#> 1 * 7 = 7  2 * 7 = 14  3 * 7 = 21  4 * 7 = 28  5 * 7 = 35  6 * 7 = 42  7 * 7 = 49  
#> 1 * 8 = 8  2 * 8 = 16  3 * 8 = 24  4 * 8 = 32  5 * 8 = 40  6 * 8 = 48  7 * 8 = 56  8 * 8 = 64  
#> 1 * 9 = 9  2 * 9 = 18  3 * 9 = 27  4 * 9 = 36  5 * 9 = 45  6 * 9 = 54  7 * 9 = 63  8 * 9 = 72  9 * 9 = 81

对非向量的 for 循环

# 分别对矩阵 u 和 v 执行线性回归
u = matrix(c(1, 2, 3, 1, 2, 4), ncol = 2)
v = matrix(c(8, 12, 20, 15, 10, 2), ncol = 2)
for (m in c("u", "v")) {
  z = get(m)
  fit = lm(z[ ,2] ~ z[ ,1])
  print(fit)
}
#> 
#> Call:
#> lm(formula = z[, 2] ~ z[, 1])
#> 
#> Coefficients:
#> (Intercept)       z[, 1]  
#>     -0.6667       1.5000  
#> 
#> 
#> Call:
#> lm(formula = z[, 2] ~ z[, 1])
#> 
#> Coefficients:
#> (Intercept)       z[, 1]  
#>      23.286       -1.071

for - next 语句

# 编程序计算 1+2+3+4+6+7 的值
x = 1:7
sum = 0
for (i in x) {
  if (i == 5) next
  sum = sum + i
}
print(sum)
#> [1] 23

while 循环

i = 1
while (i <= 10) {
  i = i + 4
}
print(i)
#> [1] 13

while 和 break 语句

i = 1
while (TRUE) {
  i = i + 4
  if (i > 10) break
}
print(i)
#> [1] 13

repeat 和 break 语句

i = 1
repeat {
  i = i + 4
  if (i > 10) break
}
print(i)
#> [1] 13

if - else 语句

# 如果 x = 2,则 y = x,否则 y = x + 1
x = 3
if (x == 2) {
  y = x
} else {
  y = x + 1
}
print(y)
#> [1] 4

switch 语句

feelings = c("sad", "afraid")
for (i in feelings) {
  x = switch(
    i,
    happy = "I am glad you are happy",
    afraid = "There is nothing to fear",
    sad = "Cheer up",
    angry = "Calm down now"
  )
  print(x)
}
#> [1] "Cheer up"
#> [1] "There is nothing to fear"

编写函数

# 编写函数(统计奇数个数)
oddcount = \(x) {
  k = 0
  for (i in x) {
    if (i %% 2 == 1) k = k + 1
  }
  return(k)
}

## 测试函数
x = 1:10
oddcount(x)
#> [1] 5