There must be a very basic thing I am not getting...
I'm working with some entropy functions and the convention is to use
log(0)=0.
So I wrote a function:
llog<-function(x){
if (x ==0) 0 else log(x)
}
which seems to work fine for individual numbers e.g.
>llog(0/2)
[1] 0
but if I try whole vectors or tables:
p<-c(4,3,1,0)
q<-c(2,2,2,2)
llog(p/q)
I get this:
[1] 0.6931472 0.4054651 -0.6931472 -Inf
What am I missing?
Thanks!
Maja
--
View this message in context:
http://n4.nabble.com/function-to-set-log-0-0-not-working-on-tables-or-vectors-tp1016278p1016278.html
Sent from the R help mailing list archive at Nabble.com.
Peter Ehlers
2010-Jan-18 02:18 UTC
[R] function to set log(0)=0 not working on tables or vectors
Are you telling us the whole story? Or did you also get a warning message which should have twigged the answer for you? Try ifelse() instead of if(). -Peter Ehlers maiya wrote:> There must be a very basic thing I am not getting... > > I'm working with some entropy functions and the convention is to use > log(0)=0. > > So I wrote a function: > > llog<-function(x){ > if (x ==0) 0 else log(x) > } > > which seems to work fine for individual numbers e.g. > >> llog(0/2) > [1] 0 > > but if I try whole vectors or tables: > > p<-c(4,3,1,0) > q<-c(2,2,2,2) > llog(p/q) > > I get this: > > [1] 0.6931472 0.4054651 -0.6931472 -Inf > > > What am I missing? > > Thanks! > > Maja-- Peter Ehlers University of Calgary 403.202.3921
David Winsemius
2010-Jan-18 03:12 UTC
[R] function to set log(0)=0 not working on tables or vectors
On Jan 17, 2010, at 8:17 PM, maiya wrote:> > There must be a very basic thing I am not getting... > > I'm working with some entropy functions and the convention is to use > log(0)=0. >I suppose the outcome of that effort may depend on whether you have assumed the needed godlike capacities to change the laws of mathematics. But I suppose that as the Earth mother that might occur to you. Go ahead, define a new mathematics. -- David> So I wrote a function: > > llog<-function(x){ > if (x ==0) 0 else log(x) > } > > which seems to work fine for individual numbers e.g. > >> llog(0/2) > [1] 0 > > but if I try whole vectors or tables: > > p<-c(4,3,1,0) > q<-c(2,2,2,2) > llog(p/q) > > I get this: > > [1] 0.6931472 0.4054651 -0.6931472 -Inf > > > What am I missing? > > Thanks! > > MajaDavid Winsemius, MD Heritage Laboratories West Hartford, CT