[R] how to export density_function output?

Duncan Murdoch murdoch at stats.uwo.ca
Mon Nov 7 15:48:36 CET 2005


Alessandro Bigi wrote:
> Dear all,
> 
> quite a naive question: I have a data frame and I computed "the kernel 
> density estimate" with density on each column.
> Now I'd like to export in a txt file the density function output for each 
> column, but, when if I use write.table, I get a message "Error in 
> as.data.frame.default(x[[i]], optional = TRUE) : can't coerce class 
> "density" into a data.frame"
> How should I do?

When you get errors like that, it's a good idea to look inside the 
object to see what's there.  For example,

 > d <- density(precip, bw = bw)
 > str(d)
List of 7
  $ x        : num [1:512] -4.82 -4.65 -4.49 -4.32 -4.16 ...
  $ y        : num [1:512] 4.79e-05 5.46e-05 6.19e-05 7.00e-05 7.91e-05 ...
  $ bw       : num 3.94
  $ n        : int 70
  $ call     : language density.default(x = precip, bw = bw)
  $ data.name: chr "precip"
  $ has.na   : logi FALSE
  - attr(*, "class")= chr "density"

So the result is a list with x and y components giving the density, plus 
other components that describe what is there.  You probably only want 
the y components from various fits.  You can extract them as

results <- data.frame(precip = d$y, ...)

(where the ... has you extracting densities from other objects).

Duncan Murdoch




More information about the R-help mailing list