At the entrance there is a file on the company's quotes (say, APPLE) in the following format:

Apple quotes data from 2001 to 2018

The task is to derive for each of the years the number of trading days this year. As I understand it, you need to make data.frame from the Date column and then somehow divide the dates into years, but it doesn’t work out (split dates). Tell me how you can solve this problem.

    1 answer 1

    The question does not indicate the source of the data, nor the type of object in which this data is stored. I would venture to suggest that this is an object of type xts . If this is the case, the solution will extract the index from the xts object, then extract the year and count the number of records.

     library(quantmod) getSymbols("AAPL") table(as.POSIXlt(index(AAPL))$year + 1900) #> 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 #> 251 253 252 252 252 250 252 252 252 252 251 61 

    The xts object xts also be converted to data.frame .

    You can extract a year from a Date object using the functions format ( as.integer(format(x, "%Y")) ), lubirate::year or using the method above.