morphy_richards morphy_richards - 2 months ago 6
R Question

calculating mean of subset between two dates

I am to calculate the mean of values (market closing prices, denoted as "Close") between two dates, based on following data set:

The answer to this task is structured as follows:

mean(subset(d, as.Date(d$Date) >= as.Date(start) & as.Date(d$Date) <= as.Date(end))$Close)

However, I don't understand this part:


Does that mean, that mean is calculated only on "Close" category of the data frame? I have looked in the documentation of the "mean" function but I haven't encountered such syntax.

I would be very grateful for an explanation


It isn't a syntax of mean it is a series of commands nested inside the function. The coder who wrote that could have broken the command into separate pieces to understand better:

#logical index
dateindex <- as.Date(d$Date) >= as.Date(d$start) & as.Date(d$Date) <= as.Date(d$end)

#subset data by index
dsubset <- subset(d, dateindex)

#find mean of 'Close' column