如何重写"sapply"命令以提高性能?

tfl*_*tre 5 performance r plyr sapply

我有一个名为"d"的〜大约1,300,000行和4列,另一个data.frame名为"gc"~12,000行和2列(但请参见下面的小例子).

d <- data.frame( gene=rep(c("a","b","c"),4), val=rnorm(12), ind=c( rep(rep("i1",3),2), rep(rep("i2",3),2) ), exp=c( rep("e1",3), rep("e2",3), rep("e1",3), rep("e2",3) ) )
gc <- data.frame( gene=c("a","b","c"), chr=c("c1","c2","c3") )
Run Code Online (Sandbox Code Playgroud)

以下是"d"的样子:

   gene         val ind exp
1     a  1.38711902  i1  e1
2     b -0.25578496  i1  e1
3     c  0.49331256  i1  e1
4     a -1.38015272  i1  e2
5     b  1.46779219  i1  e2
6     c -0.84946320  i1  e2
7     a  0.01188061  i2  e1
8     b -0.13225808  i2  e1
9     c  0.16508404  i2  e1
10    a  0.70949804  i2  e2
11    b -0.64950167  i2  e2
12    c  0.12472479  i2  e2
Run Code Online (Sandbox Code Playgroud)

这是"gc":

  gene chr
1    a  c1
2    b  c2
3    c  c3
Run Code Online (Sandbox Code Playgroud)

我想通过合并"gc"中与第一列"d"匹配的数据,将第5列添加到"d".目前我正在使用sapply.

d$chr <- sapply( 1:nrow(d), function(x) gc[ gc$gene==d[x,1], ]$chr )
Run Code Online (Sandbox Code Playgroud)

但是在实际数据上,它需要"非常长"的时间(我使用"system.time()"运行命令超过30分钟,但仍然没有完成).

你知道我怎么能以聪明的方式改写它吗?或者我应该考虑使用plyr,也许使用"并行"选项(我的计算机上有四个核心)?在这种情况下,最好的语法是什么?

提前致谢.

Sac*_*amp 12

我想你可以只使用因子作为索引:

gc[ d[,1], 2]
 [1] c1 c2 c3 c1 c2 c3 c1 c2 c3 c1 c2 c3
Levels: c1 c2 c3
Run Code Online (Sandbox Code Playgroud)

做同样的事情:

 sapply( 1:nrow(d), function(x) gc[ gc$gene==d[x,1], ]$chr )
 [1] c1 c2 c3 c1 c2 c3 c1 c2 c3 c1 c2 c3
Levels: c1 c2 c3
Run Code Online (Sandbox Code Playgroud)

但要快得多:

> system.time(replicate(1000,sapply( 1:nrow(d), function(x) gc[ gc$gene==d[x,1], ]$chr )))
   user  system elapsed 
   5.03    0.00    5.02 
> 
> system.time(replicate(1000,gc[ d[,1], 2]))
   user  system elapsed 
   0.12    0.00    0.13 
Run Code Online (Sandbox Code Playgroud)

编辑:

扩大我的评论.该gc数据帧需要的每个级别一行gene在这个级别的工作顺序:

 d <- data.frame( gene=rep(c("a","b","c"),4), val=rnorm(12), ind=c( rep(rep("i1",3),2), rep(rep("i2",3),2) ), exp=c( rep("e1",3), rep("e2",3), rep("e1",3), rep("e2",3) ) )
gc <- data.frame( gene=c("c","a","b"), chr=c("c1","c2","c3") )

gc[ d[,1], 2]
 [1] c1 c2 c3 c1 c2 c3 c1 c2 c3 c1 c2 c3
Levels: c1 c2 c3

sapply( 1:nrow(d), function(x) gc[ gc$gene==d[x,1], ]$chr )
 [1] c2 c3 c1 c2 c3 c1 c2 c3 c1 c2 c3 c1
Levels: c1 c2 c3
Run Code Online (Sandbox Code Playgroud)

但要解决这个问题并不困难:

levels(gc$gene) <- levels(d$gene) # Seems redundant as this is done right quite often automatically
gc <- gc[order(gc$gene),]


gc[ d[,1], 2]
 [1] c2 c3 c1 c2 c3 c1 c2 c3 c1 c2 c3 c1
Levels: c1 c2 c3

sapply( 1:nrow(d), function(x) gc[ gc$gene==d[x,1], ]$chr )
 [1] c2 c3 c1 c2 c3 c1 c2 c3 c1 c2 c3 c1
Levels: c1 c2 c3
Run Code Online (Sandbox Code Playgroud)