2015 春节
2015 Chinese New Year

——王安石的《元日》

2015年我们会继续努力，写有价值的文章，做好科研，也希望能通过温和的方式，得到其他科研同行的肯定。此外，希望看到这里的各位 新春快乐！

•  February 19, 2015

R函数式编程
Functional Programming in R

R语言的循环很慢，同时语法有很复杂，陷阱很多。举例来说，逐行遍历一个矩阵有两种写法：

（1）

for (i in seq_len(nrow(m))){print(i)}

（2）

for (i in 1:nrow(m)){print(i)}

> m <- matrix(, nr = 0, nc = 0)
> for (i in seq_len(nrow(m))){print(i)}
> for (i in 1:nrow(m)){print(i)}
[1] 1
[1] 0

l <- as.list(seq(9, 1, -1))
d <- data.frame(a = c(1, 2), b = c(3, 4))
m <- matrix(seq(9, 1, -1), 3, 3)
v <- seq(9, 1, -1)

isEven <- function(x) { x %% 2 == 0 }
isEven(1:3)

Filter(isEven, l)
## Filter(isEven, d) ## this does not work
Filter(isEven, m)
Filter(isEven, v)

Position(isEven, l)
# Position(isEven, d) ## this does not work
Position(isEven, m)
Position(isEven, v)

Find(isEven, l)
# Find(isEven, d) ## this does not work
Find(isEven, m)
Find(isEven, v)

library(microbenchmark)
v <- seq(10000)
m1 <- function(v) {
v[v%%2 == 0]
}
m2 <- function(v) {
res <- vector()
for(i in v) {
if (i %% 2 == 0) {
res <- c(res, i)
}
}
res
}
m3 <- function(v) {
Filter(isEven, v)
}

microbenchmark(res1 <- m1(v),
res2 <- m2(v),
res3 <- m3(v), times = 1000)

Unit: microseconds
expr       min        lq       mean    median         uq       max neval
res1 <- m1(v)   341.038   348.526   529.9475   356.225   380.6965  58359.46  1000
res2 <- m2(v) 33687.987 38433.148 48014.3656 39791.000 41751.3955 303604.96  1000
res3 <- m3(v)  6178.547  6648.369  8493.9365  6999.976  7445.0725 124781.90  1000