[R] calculating median with a condition
James W. MacDonald
jmacdon at med.umich.edu
Mon Jul 20 21:29:21 CEST 2009
Hi Manisha,
Manisha Brahmachary wrote:
> Hello,
>
>
>
> I am trying to calculate the median of numbers across each row for the data
> shown below , with the condition that if the number is negative, that it
> should be ignored and the median should be taken of only the positive
> numbers.
>
>
>
> For eg: data is in Column A,B,C. Column D and E demonstrates what I want to
> get as answer
>
>
>
> A
>
> B
>
> C
>
> Median
>
> median value
>
> -13.6688115
>
> -32.50914055
>
> -50.54011892
>
> all negative, so ignore
>
> NA
>
> NA
>
> -53.65656268
>
> 42.58599666
>
> median C
>
> 42.58599666
>
> 33.30683089
>
> 18.93765489
>
> -25.17024229
>
> median A,B
>
> 26.12224289
>
>
>
> The R script I have written is below( which doesnot do the job properly)
>
>
>
> median.value<- matrix(nrow=nrow(data),ncol=1)
>
> for(k in 1:nrow(data)){
>
> median.value[k]<-median(data[which(data[k,]>0)])}
meds <- apply(data, 1, function(x) ifelse(median(x) < 0, median(x[x >=
0]), median(x)))
I would normally avoid variable names like data, as you are masking a
function by the same name.
Best,
Jim
>
>
>
> Can someone suggest me the correct R script to do what I have explained
> above.
>
>
>
> Thanks
>
> Manisha
>
>
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
--
James W. MacDonald, M.S.
Biostatistician
Douglas Lab
University of Michigan
Department of Human Genetics
5912 Buhl
1241 E. Catherine St.
Ann Arbor MI 48109-5618
734-615-7826
More information about the R-help
mailing list