转换R中的代码以提高效率

时间:2016-04-14 12:17:28

标签: r

我必须遵循以下代码:

   WBP2=lapply(1:2500,function(j){as.data.frame(lapply(1:10000,function(i)
   {rowSums(data.frame((mapply(`*`,Theta[[j]],t(W[i,]),SIMPLIFY=FALSE))))}))})

W是矩阵80列和10000行,Theta是2500个矩阵,包含1000行和80列。我们的目标是为每2500次模拟创建10000个数据帧。每个data.frame将是一行W(W [i,])乘以theta [[j]]的所有行的结果(因此是80列和1000行的组合)。我们只需要这个组合的每一行的总和,因此需要一列和1000行的data.frame

这是一个可重现的代码

W=matrix((1:80), nrow =10, ncol=4)

theta= lapply(1:5,function(j){matrix((41:60),nrow=5,ncol=4)})

WBP=lapply(1:5,function(j){as.data.frame(lapply(1:10,function(i)  
{rowSums(data.frame(as.matrix(theta[[j]])%*%as.numeric(t(W[i,]))))}))})

View(WBP[[1]])

正如您所看到的,它非常沉重,我的电脑无法实现这样的功能。

有没有办法可以让它更高效,更省时?

谢谢!!!

1 个答案:

答案 0 :(得分:0)

你只能使用一个lapply

喜欢:

#header { clear:both; width: 100%; background-color: darkorange; border-top: 1px solid #d2d2d3; border-bottom: 1px solid #d2d2d3; margin: 20px 0px 20px 0px;}


h1.head {font-family: verdana; font-size: 200%;}

a { color: orange;}

.sidebar { float: left; width: 25%; height: 100%;}

#text { float: right; width: 70%;}

body { text-align:center;}

p, p a {text-align: left; font-size: 90%;}

#bar-fixed { position: fixed; }

或使用<body> <div id="header"> <h1 class="head"><b>Hello, world ?</b></h1> </div> <div id="bar-fixed"> <div class="sidebar"> <p class="bar"><a href="#"> Make this fixed when scroll</a></p> <p class="bar"><a href="#"> Make this fixed when scroll</a></p> <p class="bar"><a href="#"> Make this fixed when scroll</a></p> <p class="bar"><a href="#"> Make this fixed when scroll</a></p> <p class="bar"><a href="#"> Make this fixed when scroll</a></p> </div> </div> <div id="text"> <p>I want the sidebar fixed when i scroll down over the Header. and the sidebar will go up LIKE STICKY SIDEBAR</p> <p>I want the sidebar fixed when i scroll down over the Header. and the sidebar will go up LIKE STICKY SIDEBAR</p> <p>I want the sidebar fixed when i scroll down over the Header. and the sidebar will go up LIKE STICKY SIDEBAR</p> <p>I want the sidebar fixed when i scroll down over the Header. and the sidebar will go up LIKE STICKY SIDEBAR</p> <p>I want the sidebar fixed when i scroll down over the Header. and the sidebar will go up LIKE STICKY SIDEBAR</p> <p>I want the sidebar fixed when i scroll down over the Header. and the sidebar will go up LIKE STICKY SIDEBAR</p> <p>I want the sidebar fixed when i scroll down over the Header. and the sidebar will go up LIKE STICKY SIDEBAR</p> <p>I want the sidebar fixed when i scroll down over the Header. and the sidebar will go up LIKE STICKY SIDEBAR</p> </div> </body>

wbp1=function()lapply(1:5,function(j){as.data.frame(as.matrix(theta[[j]])%*%as.matrix(t(W)))})

benchamrk

你的变种

tcrossprod

结果相同(仅名称不同)wbp2=function()lapply(1:5,function(j){as.data.frame(tcrossprod(as.matrix(theta[[1]]),as.matrix(W)))})