R Question

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

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

Answer Source

You could simply do ratio[mcap<100]<-NA.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download