morphy_richards - 1 year ago 88
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:

http://r-exercises.com/wp-content/uploads/2016/07/data.csv

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:

``````mean(...)\$Close
``````

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

Answer Source

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
mean(dsubset\$Close)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download