本文编辑版本:R version 3.5.0
一、 循环for while语句
回顾R中的数据结构,假设:
x <- c(5, 2, 6, 8, 4, 2)
这是一个简单求和然后求均值的问题,对于一个vector,求每个数的总和,你可以简单地写出: sum(x)/n 或者mean(x)来求均值(没人会说这不行)。当然为了教学,我想在这里引出循环来解决这个问题:
n <- length(x)
sum.x <- 0
for(i in 1:n){ # loop repeated n times
# compute cumulative sum
sum.x <- sum.x + x[i]
print(i) # print index value in each iteration (for debugging)
} # end for loop
# compute average
sum.x/n
for loop里面的i,只是一个代号,你可以把它换成m、n之类的未被定义的字符,效果是一样的(但是我不推荐)。同时,你也可以使用while loop来解决这个问题:
# average the numbers in vector x using a while() loop
sum