[R] calculating median with a condition
Chuck Cleland
ccleland at optonline.net
Mon Jul 20 21:31:19 CEST 2009
On 7/20/2009 2:59 PM, 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)])}
>
>
>
> Can someone suggest me the correct R script to do what I have explained
> above.
X <- as.data.frame(matrix(rnorm(100), ncol=10))
apply(X, 1, function(x){median(x[x > 0])})
[1] 0.2297943 0.6476565 0.4699609 0.8744830
[5] 1.0242502 0.7800703 0.6648436 0.2930191
[9] 0.6001506 1.0767194
> 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.
--
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894
More information about the R-help
mailing list