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

Mark Sharp msharp at txbiomed.org
Thu Oct 20 18:20:31 CEST 2016


You have to assign cnt and new value in the loop if you want it to update in the loop. However, to count the number of values of x > median(x), there are multiple options. You are using a loop where none is needed in R, which has many implicit vector functions that run with relational operators and assignments.

x <- rnorm(10)
cnt <- sum(ifelse(x > median(x), 1, 0))

Because TRUE evaluates to 1 and FALSE evaluates to 0, you can also use
cnt <- sum(x > median(x))

I cannot help you with the ggplot question directly since you have not provided a definition of the object st_chg_51.


R. Mark Sharp, Ph.D.
Director of Primate Records Database
Southwest National Primate Research Center
Texas Biomedical Research Institute
P.O. Box 760549
San Antonio, TX 78245-0549
Telephone: (210)258-9476
e-mail: msharp at TxBiomed.org

> On Oct 20, 2016, at 3:25 AM, Indhira, Anusha <Anusha.Indhira at controlsdata.com> wrote:
> 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.

CONFIDENTIALITY NOTICE: This e-mail and any files and/or...{{dropped:10}}

More information about the R-help mailing list