简体   繁体   English

如何在R中使循环更有效?

[英]How to make loops more efficient in R?

I am facing a problem with the large amount of time my code takes to run. 我遇到了运行代码需要大量时间的问题。 I have one data frame with market capitalization of certain companies and I have a second data frame with ratios. 我有一个数据框架与某些公司的市值,我有第二个数据框架与比率。 Below there is a reproducible example 下面是一个可重复的例子

AAPL <- c(500,550,600,540,580)
MSFT <- c(600,670,630,650,650)
WDC <- c(50,40,40,45,50)
mcap<- data.frame (AAPL,MSFT,WDC)

AAPL.r <- c(3,3.2,4,4.5,5)
MSFT.r <- c(6,5.8,5.7,6.3,6)
WDC.r <- c(10,8,8.2,9,9)
ratio <- data.frame (AAPL.r,MSFT.r,WDC.r)    

What I want to do is to replace the ratio by NA when the market cap is lower than 100. This is what I am doing 我想做的是在市值低于100时用NA替换比率。这就是我在做的事情

for (i in 1:5){
for (j in 1:3){
    ratio[i,j] <- ifelse (mcap[i,j]<100,NA,ratio[i,j])
}
}

However in a big data frame this is taking hours to run. 然而,在大数据框架中,这需要数小时才能运行。 Is there a more efficient way to do this? 有没有更有效的方法来做到这一点?

Thank you in advance 先感谢您

你可以简单地做一个ratio[mcap<100]<-NA

另一种可能性是使用函数is.na<-

is.na(ratio) <- mcap < 100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM