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? Thanks, Alessandro -- --
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
Alessandro Bigi <abigi <at> agrsci.unibo.it> writes:> > 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"dens = density(c(-20,rep(0,98),20)) str(dens) # If in doubt, write str() #List of 7 # $ x : num [1:512] -23.1 -23.0 -22.9 -22.8 -22.7 ... # $ y : num [1:512] 4.46e-05 5.77e-05 7.40e-05 9.45e-05 1.20e-04 ... # $ bw : num 1.02 # $ n : int 100 # $ call : language density.default(x = c(-20, rep(0, 98), 20)) # $ data.name: chr "c(-20, rep(0, 98), 20)" # $ has.na : logi FALSE # - attr(*, "class")= chr "density" # You probably need x and y write.table(cbind(dens$x,dens$y),file="dens.txt")
Seemingly Similar Threads
- matrix transformation into 3 columns II.
- Function that is giving me a headache- any help appreciated (automatic read )
- How to replace numeric value in the column contains Text (Factor)?
- R combining vectors into a data frame but without a continuous common variable
- summing 15 minute precip data to daily