# 笨办法学R编程（5）

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

`# 预备练习mat <- matrix(1:12,ncol=4)print(mat)t(mat)colnames(mat) <- c('one','two','three','four')rownames(mat) <- c('a','b','c')print(mat)apply(mat,1,sum)apply(mat,2,sum)sum(apply(mat,2,sum))prod(apply(mat,2,sum)) # 之前建立的判断是否为质数的函数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)}x = 1:20prime <- x[sapply(x,findprime)] #  欧拉问题五，寻找最小的能被1到20所整除的数。`
`# 建立分解质因子的函数primefactor <- function(x,prime) {  m <- length(prime)  fac.count <- numeric(m)  names(fac.count) <- prime  for (i in 1:m) {    prime.num <- prime[i]    while (x %% prime.num == 0 & x !=1 ) {      fac.count[i] <- fac.count[i] + 1      x = x / prime.num    }    }  return(fac.count)} # 上面的函数负责对一个20以下的数分解为多个质数之积# 返回每个质因子对应的自乘次数primefactor(18,prime) # 对1到20每个数进行质因子分解，形成一个表格result <- t(sapply(1:20,primefactor,prime))# 求每列的极大值prime.power <- apply(result,2,max)prod(prime^prime.power)`