[R] Relase positive with log and zero of negative with 0

David Winsemius dwinsemius at comcast.net
Mon Nov 16 15:05:57 CET 2009


On Nov 16, 2009, at 8:55 AM, Peter Ehlers wrote:

>
>
> David Winsemius wrote:
>> 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."
> Here is one more way, somewhat less transparent, motivated
> by the examples on the ?ifelse page:
>
> x <- log(ifelse(x > 0, x, 1))

Here's yet another motivated by the above:

 > log( (x<=0) + (x>0)*x )
[1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 0.0000000  
0.0000000

>
> -Peter Ehlers
>> -- 
>> David Winsemius, MD
>> Heritage Laboratories
>> West Hartford, CT
>> ______________________________________________
>> 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list