Your code, cnt = 0 for(i in 1:length(x)){ ifelse(x[i] > median(x),cnt+1,cnt) } sets cnt to zero and never sets it to anything else. Hence it is zero at the end of the loop. if you set cnt to the value of your call to ifelse you should get the desired result cnt <- ifelse(x[i] > median(x),cnt+1,cnt)
By the way, the more R-ish way of counting the number of x strictly greater than the median is just cnt <- sum(x > median(x)) instead of those 4 lines above. ('cnt' should be about length(x)/2 unless there are a lot of points at the median). Bill Dunlap TIBCO Software wdunlap tibco.com On Thu, Oct 20, 2016 at 1:25 AM, Indhira, Anusha < anusha.indh...@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@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. > [[alternative HTML version deleted]] ______________________________________________ R-help@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.