[R] need help in customising function in stat_summary function ggplot2

David L Carlson dcarlson at tamu.edu
Thu Oct 20 17:33:57 CEST 2016


You do know that the median is defined as the point with half the values above it and half below it? For even sample sizes it will always be 50%.

Your function is not working because you used the ifelse() function instead of the programming command if() else:

> ?Control # Note the capital "C"
> ?ifelse

But you do not understand basic R so you should spend some time using a tutorial before you try to write functions. 

> set.seed(42)    # Set random number seed
> x <- rnorm(100) # Draw 100 random normal values with mean=0 and sd=1
> sum(x > median(x))/length(x)*100  # Compute the % greater than the median
[1] 50

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352


-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Indhira, Anusha
Sent: Thursday, October 20, 2016 3:26 AM
To: r-help at r-project.org
Subject: [R] need help in customising function in stat_summary function ggplot2

Hi,

I would like to print percentage of points in a group which are greater than median value in boxplot. I have tried below code but it always prints zero in the graph. Can you let me know, how to modify code to get desired result?


perc.greaterthan.median <- function(x){
  cnt = 0
  for(i in 1:length(x)){
   ifelse(x[i] > median(x),cnt+1,cnt)
  }
  return(c(y = median(x)*1.7, label = round((cnt/length(x))*100,2)))
}

ggplot(st_chg_51, aes(x=factor(st_dv), P3))+ #label=rownames(st_chg_51))) +
  geom_boxplot(fill = "grey80", colour = "#3366FF") +
  stat_summary(fun.data = perc.greaterthan.median, geom = "text", fun.y = median) +
  theme_bw()+theme(axis.text = element_text(angle = 90, hjust = 1))

Why does cnt in the function doesn't get incremented in the loop?

Thanks,
Anusha

This e-mail (including attachments) contains contents owned by Rolls-Royce plc and its subsidiaries, affiliated companies or customers and covered by the laws of England and Wales, Brazil, US, or Canada (federal, state or provincial). The information is intended to be confidential and may be legally privileged. If you are not the intended recipient, you are hereby notified that any retention, dissemination, distribution, interception or copying of this communication is strictly prohibited and may subject you to further legal action. Reply to the sender if you received this email by accident, and then delete the email and any attachments.

	[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list