Skip to content
Prev 206598 / 398506 Next

function to set log(0)=0 not working on tables or vectors

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.
[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