user3203275
user3203275

Reputation: 305

na.omit function is not removing rows containing NA

Hi there I am looking on the internet what is wrong and the na.omit() function is not removing the rows with NA. Could you please help me?

library(TTR)
library(quantmod)
library(doParallel) #this library is for parallel core processing

StartDate = "2010-01-01"
EndDate = "2020-03-20"
myStock <- c("AMZN")
getSymbols(myStock, src="yahoo", from=StartDate, to=EndDate)

gdat <-coredata(AMZN$AMZN.Close) # Create a 2-d array of all the data. Or...
Data <- data.frame(date=index(AMZN), coredata(AMZN)) # Create a data frame with the data and (optionally) maintain the date as an index

Data$rsi22 <- data.frame(RSI(Cl(Data), n=22))
Data$rsi44 <- data.frame(RSI(Cl(Data), n=44))
colnames(Data)

DatanoNA <- na.omit(Data) #remove rows with NAs

Upvotes: 0

Views: 1975

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226182

I think you're looking for the complete.cases() function. na.omit() is for removing NA values in a vector, not for removing rows containing NA values from a data frame.

Also, your data frame construction is a little wonky (see below for more explanation). Try this:

Data <- data.frame(date=index(AMZN), coredata(AMZN),
                  rsi22=RSI(Cl(Data), n=22),
                  rsi44=RSI(Cl(Data), n=44))
nrow(Data)
nrow(Data[complete.cases(Data),])

Normally every column of a data frame is a vector. The results of RSI() are stored as a vector. When you say

Data$rsi22 <- data.frame(RSI(Cl(Data), n=22))

what you're doing is wrapping the results in a data frame and then embedding it an another data frame (Data), which is something you can legally do in R but which is unusual and confuses a lot of the standard data-processing functions.

Upvotes: 2

cmirian
cmirian

Reputation: 2253

You could try complete.cases

DatanoNA <- Data[complete.cases(Data),]

Upvotes: 0

Related Questions