Why does log applied to a vector with a magrittr pipe give unexpected & incorrect values?

Viewed 230

I am trying to compute the entropy of a discrete distribution and I noticed the behavior using magrittr is not what I expected. To give an example:

> x <- c("A","B","C","A","A","D")                                                                                                 
> table(x)/length(x) %>% log2                                                                                                     
x
        A         B         C         D
 1.1605584 0.3868528 0.3868528 0.3868528

Which is not correct---the logs of values less than 1 should be negative. If I break up the steps, I get the correct answer:

> freq <- table(x)/length(x)                                                                                                      
> log2(freq)                                                                                                                      
 x
         A         B         C         D
 -1.000000 -2.584963 -2.584963 -2.584963
2 Answers
Related