R中的程序结构(for,while,repeat)

xiaoxiao2021-02-28  79

1、程序结构-for循环

1:5 for(i in 1:5) print(i) ss <- seq(from=1, to=10, by=0.1) for(s in ss) { print(s) } df = data.frame( age=c(21, 22, 23), name=c('KEN', 'John', 'JIMI'), stringsAsFactors = FALSE ); #如果用in进行遍历data.frame,那么默认按列遍历 for(l in df) { print(l); print(l['age']) print(l['name']) print("---------------------") } for(i in 1:nrow(df)) { l <- df[i, ] print(l); print(l['age']) print(l['name']) print("---------------------") }

2、程序结构-while循环

i = 0 while(i<5) { i <- i+1; print(1:i); } i = 0 while(i<5) { i <- i+1 if(i==4) { next; } print(1:i); } i = 0 while(TRUE) { i <- i+1 if(i==4) { next; } print(1:i); if(i==10) { break; } }

3、程序结构-repeat循环

i = 0 repeat { i <- i+1 if(i==4) { next; } print(1:i); if(i==10) { break; } }

#注意:repeat循环是一个死循环,相当于while(true),需要使用break跳出。

转载请注明原文地址: https://www.6miu.com/read-84842.html

最新回复(0)