Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

combining 2 series and dropping NA in R

I am trying to combing the dividend history of 2 different stocks and I have the below code:

library(quantmod)
library(tidyr)
AAPL<-round(getDividends("AAPL"),4)
MSFT<-round(getDividends("MSFT"),4)
dividend<-(cbind(AAPL,MSFT))

As the 2 stocks pay out dividend on different dates so there will be NAs after combining and so I try to use drop_na function from tidyr like below:

drop_na(dividend)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#Error in UseMethod("drop_na") :
no applicable method for ‘drop_na’ applied to an object of class "c(‘xts’, ‘zoo’)"

May I know what did I do wrong here? Many thanks for your help.

Update 1:

Tried na.omit, which returns with the following:

> dividend<-(cbind(AAPL,MSFT))%>%
>  na.omit(dividend)%>%
>  print(dividend)
     [,1] [,2]

>Solution :

drop_na only works on data frames but even if you converted it to data frame it would not give what you want. Every row contains an NA so drop_na and na.omit would both remove every row leaving a zero row result.

Instead try aggregating over year/month which gives zoo object both. If you need an xts object use as.xts(both) .

both <- aggregate(dividend, as.yearmon, sum, na.rm = TRUE)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading