rkevinburton at charter.net
2009-Nov-15 15:18 UTC
[R] Relase positive with log and zero of negative with 0
This is a very simple question but I couldn't form a site search quesry that would return a reasonable result set. Say I have a vector: x <- c(0,2,3,4,5,-1,-2) I want to replace all of the values in 'x' with the log of x. Naturally this runs into problems since some of the values are negative or zero. So how can I replace all of the positive elements of x with the log(x) and the rest with zero? Thank you. Kevin
Berwin A Turlach
2009-Nov-15 15:27 UTC
[R] Relase positive with log and zero of negative with 0
G'day Kevin, On Sun, 15 Nov 2009 7:18:18 -0800 <rkevinburton at charter.net> wrote:> This is a very simple question but I couldn't form a site search > quesry that would return a reasonable result set. > > Say I have a vector: > > x <- c(0,2,3,4,5,-1,-2) > > I want to replace all of the values in 'x' with the log of x. > Naturally this runs into problems since some of the values are > negative or zero. So how can I replace all of the positive elements > of x with the log(x) and the rest with zero?If you do not mind a warning message: R> x <- c(0,2,3,4,5,-1,-2) R> x <- ifelse(x <= 0,0, log(x)) Warning message: In log(x) : NaNs produced R> x [1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 0.0000000 0.0000000 If you do mind, then: R> x <- c(0,2,3,4,5,-1,-2) R> ind <- x>0 R> x[!ind] <- 0 R> x[ind] <- log(x[ind]) R> x [1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 0.0000000 0.0000000 HTH. Cheers, Berwin ========================== Full address ===========================Berwin A Turlach Tel.: +61 (8) 6488 3338 (secr) School of Maths and Stats (M019) +61 (8) 6488 3383 (self) The University of Western Australia FAX : +61 (8) 6488 1028 35 Stirling Highway Crawley WA 6009 e-mail: berwin at maths.uwa.edu.au Australia http://www.maths.uwa.edu.au/~berwin
David Winsemius
2009-Nov-15 15:33 UTC
[R] Relase positive with log and zero of negative with 0
On Nov 15, 2009, at 10:18 AM, <rkevinburton at charter.net> wrote:> This is a very simple question but I couldn't form a site search > quesry that would return a reasonable result set. > > Say I have a vector: > > x <- c(0,2,3,4,5,-1,-2) > > I want to replace all of the values in 'x' with the log of x. > Naturally this runs into problems since some of the values are > negative or zero. So how can I replace all of the positive elements > of x with the log(x) and the rest with zero?> x <- c(0,2,3,4,5,-1,-2) > x <- ifelse(x>0, log(x), 0) Warning message: In log(x) : NaNs produced > x [1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 0.0000000 0.0000000 The warning is harmless as you can see, but if you wanted to avoid it, then: > x[x<=0] <- 0; x[x>0] <-log(x[x>0]) In the second command, you need to have the logical test on both sides to avoid replacement " out of synchrony." -- David Winsemius, MD Heritage Laboratories West Hartford, CT