# 笨办法学R编程（3）

 This post was kindly contributed by 数据科学与R语言 - go there to comment and to read the full post.

`# 预备练习，学习for循环、建立自定义函数和其它一些函数 for (n in 1:10) {    print(sqrt(n))} x <- c('hello','world','I','love','R')for (n in x) {    print(n)}x <- seq(from=1,to=10,by=1)print(x)x <- seq(from=1,to=10,by=2)print(x)x <- seq(from=1,to=2,length.out=10)print(x)round(x) x > 1.5all(x>1.5)any(x>1.5) # 如何自定义一个求圆面积的函数myfunc <- function(r) {    area <- pi*r^2    return(area)}print(myfunc(4)) # 同时求四个不同半径圆的面积r <- c(2,2,4,3)sapply(X=r,FUN=myfunc) # Project Euler 3# 找到600851475143这个数的最大质因子# 先建立一个函数以判断某个数是否为质数 findprime  <- function(x) {    if (x %in% c(2,3,5,7)) return(TRUE)    if (x%%2 == 0 | x==1) return(FALSE)    xsqrt <- round(sqrt(x))    xseq <- seq(from=3,to=xsqrt,by=2)    if (all(x %% xseq !=0)) return(TRUE)    else return(FALSE)}# 列出1到100的质数，看函数对不对x = 1:100x[sapply(x,findprime)] # 寻找最大的质因子n <- 600851475143for (i in seq(from=3, to=round(sqrt(n)), by=2)) {  if (findprime(i) & n %% i == 0) {      n <- n / i      prime.factor <- i             if (i >= n)        break    }}print(prime.factor)`