您的位置首页百科知识

R语言for循环用法

R语言for循环用法

的有关信息介绍如下:

R语言for循环用法

跟大家分享下R语言里for循环的用法

打开R语言或RStudio

我们想让R语言自动循环5次,每次都输出111,则代码如下:

for(i in 1:5) print(111)

假如我们想让这5次分别输出1、输出2、输出3...到输出5,则代码如下:

for(i in 1:5) print(i)

还可以用for循环做其他的事,例如:

for(j in 1:5) print(1:j)

又如:

for(n in c(10,20,30,40,50)) {

x <- stats::rnorm(n)

cat(n, ": ", sum(x^2), "\n", sep = ";")

}

又如:

f <- factor(sample(letters[6:10], 10, replace = TRUE))

for(j in unique(f)) print(j)

关于for循环的用法就介绍到这里。

大家可以自行尝试哦!