user10512163
user10512163

Reputation: 21

R - Aggregate.Data.Frame With Quartiles

I am new (very new) to R coding and can't seem to figure out how to get the quartiles output correct. Might be much simpler than I am finding it to be!

PLEASE HELP!

This is the code I currently have and it is working perfectly for median and mean.

MedianCol = aggregate.data.frame(
  x = list(COLVALUE=COLVALUE),
  by = list(YEAR=YEAR),
  FUN = median,
  na.rm=TRUE
)

MeanCol = aggregate.data.frame(
  x = list(COLVALUE=COLVALUE),
  by = list(YEAR=YEAR),
  FUN = mean,
  na.rm=TRUE
)

#This is where I have an issue, I don't know how to even code it
Q3Col = aggregate.data.frame(
  x = list(COLVALUE=COLVALUE),
  by = list(YEAR=YEAR),
  FUN = quantile(0.25),
  na.rm=TRUE
)

#I will have to add the quartiles in the merge below as well
MovingAverage <- merge(x = MedianCol, y = MeanCol, by = "YEAR", all = TRUE)

The Q3Col is where I need the Third Quartile value to be returned. I also need the first Quartile, Best Decile and Worst Decile.

My Data looks like this: Data

Thank you in advance!

Upvotes: 1

Views: 2628

Answers (2)

user10512163
user10512163

Reputation: 21

This is the working script that I have created. It works fine for me. Used within Tibco Spotfire.

MedianCol = aggregate.data.frame(
  x = list(Median=Median),
  by = list(YEAR=YEAR),
  FUN = median,
  na.rm=TRUE
)

Q1Col = aggregate.data.frame(
  x = list(Q1=Q1), 
  by = list(YEAR=YEAR), 
  FUN = quantile, probs = 0.25, 
  na.rm=TRUE 
)

Q3Col = aggregate.data.frame(
  x = list(Q3=Q3), 
  by = list(YEAR=YEAR), 
  FUN = quantile, probs = 0.75, 
  na.rm=TRUE 
)

P10Col = aggregate.data.frame(
  x = list(P10=P10), 
  by = list(YEAR=YEAR), 
  FUN = quantile, probs = 0.10, 
  na.rm=TRUE 
)

P90Col = aggregate.data.frame(
  x = list(P90=P90), 
  by = list(YEAR=YEAR), 
  FUN = quantile, probs = 0.90, 
  na.rm=TRUE 
)

Merge1 <- merge(x = Q1Col, y = Q3Col, by = "YEAR", all = TRUE)
Merge2 <- merge(x = P10Col, y = P90Col, by = "YEAR", all = TRUE)
MergeFinal <- merge(x = Merge1, y = Merge2, by = "YEAR", all = TRUE)
MovingAverage <- merge(x = MergeFinal, y = MedianCol, by = "YEAR", all = TRUE)

This is what was output: OUTPUT

Upvotes: 1

user10512163
user10512163

Reputation: 21

Brilliant! That did the trick. Thank you so much!!! And yes, Q3 is 0.75. My mistake on the naming!

I am using the meanCol, MedianCol, Q3Col as "variables" because I want to input these into a single "table".

How will I add the Q3Col below? I tried and I get an error. I cannot seem to add more than 2.

This works:

MovingAverage <- merge(x = MedianCol, y = MeanCol, by = "YEAR", all = TRUE)

This doesn't:

MovingAverage <- merge(x = MedianCol, y = MeanCol, z = Q3Col, by = "YEAR", all = TRUE)

Upvotes: 0

Related Questions