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
你可以简单地做一个ratio[mcap<100]<-NA
。
另一种可能性是使用函数is.na<-
。
is.na(ratio) <- mcap < 100
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.