Reputation: 1875
I have a data frame that displays sales data, split by Year, and Quarter. What I want to do is plot Demand with respect to Price, however I'd like to see price as difference from average annual price.
What I have thus far is
Year <- c(1,1,1,2,2,2,2)
Quarter <- c(1,2,3,4,1,2,3,4)
Price <- c(10,15,20,15,15,20,20,25)
Demand <- c(12,15,10,12,10,15,12,12)
sales_data <- data.frame(Year, Quarter, Price, Demand)
attach(sales_data)
plot(Price-mean(Price),Demand)
#Correct prices:
#year1 -5,0,5,0
#year2 -5,0,0,5
Of course the issue with this is that mean() uses all of data not just data from each year separately.
Upvotes: 0
Views: 48
Reputation: 25225
using base by function
plot(unlist(by(sales_data, sales_data$Year, function(x) x$Price - mean(x$Price))),Demand)
Upvotes: 1