0

I would like to divide two density distributions (or two histograms) in R. I would even take "subtract one from the other using an operator" -- but I don't see an obvious way to do it, other than sample and subtract/divide the long way.

Is there a function/R package that allows one to manipulate R densities without sampling?

I am a newbie to R, am a CERN root transplant, if that's relevant.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Just to be clear: You have the density distribution of two random variables x, y (from a sample most likely) and want to plot the density of the quotient x/y? – Ricardo Oliveros-Ramos Jun 28 '13 at 23:07
  • If you want to operate on theoretic distributions there are a family of packages for that, all beginning with the letters "distr". – IRTFM Jun 28 '13 at 23:20
  • Ricardo, yes, that is exactly what I would like. @DWin, thank you, I will look into the packages (however, the distributions are experimental samplings, so that might not work). – user2533409 Jul 01 '13 at 17:33

1 Answers1

2

The trick with operations on two (or more) densities is to set their ranges to be identical. Then the "x" vectors will be the same and the "y" vectors will be very well behaved with the usual arithmetic operations.

> xx <- rnorm(100)
> yy <- rnorm(100)

> yd <- density(yy, from=-3, to=3)
> xd <- density(xx, from=-3, to=3)

> plot(xd,  col="red")

> str(xd)
List of 7
 $ x        : num [1:512] -3 -2.99 -2.98 -2.96 -2.95 ...
 $ y        : num [1:512] 0.0122 0.0126 0.0131 0.0136 0.0141 ...
 $ bw       : num 0.377
 $ n        : int 100
 $ call     : language density.default(x = xx, from = -3, to = 3)
 $ data.name: chr "xx"
 $ has.na   : logi FALSE
 - attr(*, "class")= chr "density"

> lines(yd$x, yd$y, col="red")
#  difference of the densities
> lines(yd$x, xd$y-yd$y, col="green")
IRTFM
  • 258,963
  • 21
  • 364
  • 487