好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

R tips

R tips

How do you clear the R console in OS X (or Ubuntu)

http://stackoverflow.com/questions/4102717/how-do-you-clear-the-r-console-in-os-x-or-ubuntu

ctrl+l

http://bbs.sciencenet.cn/home.php?mod=space&uid=81938&do=blog&id=413384

为R代码提速 两条小技巧

已有 375 次阅读   2011-2-16 09:30   | 个人分类: 统计计算 | 系统分类: 科研笔记 | 关键词:R语言

一、如果需要保存数据到向量或矩阵, 首选方法 是: 新建一个向量或矩阵,然后为新建向量或矩阵赋值 。备选方法 是: 通过连接当前向量或矩阵,以生成新的向量或矩阵 。在数据量较少的情况下,上述两种方法没有明显区别,在遇到大量数据时,前者可以提高60倍效率。
小试验:
n <- 10^5
a <- NULL
#连接
system.time(for(i in 1:n){a <- c(a,1)})
#新建并赋值
b <- rep(0,n)
system.time(for(i in 1:n){b[i] <- 1})
前者耗时31.78秒,后者耗时0.44秒。

二、 能避免使用圆括号的,尽量不要使用。
小试验:
f <- function(n){  for(i in 1:n){    x <- 1/(1+x)    }}

g <- function(n){    for(i in 1:n){    x <- (1/(1+x))    }}

h <- function(n){    for(i in 1:n){    x <- (1+x)^(-1)    }}

j <- function(n){    for(i in 1:n){    x <- {1/{1+x}}    }}

k <- function(n){    for(i in 1:n){    x <- 1/{1+x}    }}
x <- 1
system.time(f(10^6))
system.time(g(10^6))
system.time(h(10^6))
system.time(j(10^6))
system.time(k(10^6))
分别耗时:1.36、1.51、1.90、1.44、1.25。

整理自:
http://statisfaction.wordpress.com/2011/01/27/speed-up-your-r-code/#comment-291
http://xianblog.wordpress.com/2011/01/30/r-exam/

查看更多关于R tips的详细内容...

  阅读:35次