[R] density(x)

Marc Schwartz MSchwartz at MedAnalytics.com
Mon Jul 5 17:05:52 CEST 2004

On Mon, 2004-07-05 at 09:41, Christoph Hanck wrote:
> Hello and thanks for your reply
> Hopefully, my answer arrives at the correct place like that (if not, I
> am sorry for bothering you, but please let me know...)
> To sum up my procedure (sp is exactly the same thing as spr, I had
> just tinkered with
> the names while trying sth. to solve this problem)
> > sp<-read.table("c:/ratsdata/sp3.txt", col.names="sp")
> > xd<-density(sp)
> Error in density(sp) : argument must be numeric
> The suggested remedies yield the following
> > str(sp)
> `data.frame':   195 obs. of  1 variable:
>  $ sp: int  11 10 10 12 25 22 12 23 13 15 ...
> > xd<-density(as.numeric(sp))
> Error in as.double.default(sp) : (list) object cannot be coerced to
> double
> Hence, it does not seem to be a factor. Declaring it as numeric gives
> another error
> message, on which I haven't yet found any help in Google/the archive.

In this case, you are trying to pass a data frame as an argument to
density() rather than a single column vector. The same problem is the
reason for the error in "xd<-density(as.numeric(sp))". You are trying to
coerce a data frame to a double.


# create a data frame called 'sp', that has a column called 'sp'
> sp <- data.frame(sp = 1:195)

> str(sp)
`data.frame':	195 obs. of  1 variable:
 $ sp: int  1 2 3 4 5 6 7 8 9 10 ...

# Now try to use density()
> density(sp)
Error in density(sp) : argument must be numeric

# Now call density() properly with the column 'sp' as an argument
# using the data.frame$column notation:
> density(sp$sp)

	density(x = sp$sp)

Data: sp$sp (195 obs.);	Bandwidth 'bw' = 17.69

       x                y            
 Min.   :-52.08   Min.   :7.688e-06  
 1st Qu.: 22.96   1st Qu.:1.009e-03  
 Median : 98.00   Median :4.600e-03  
 Mean   : 98.00   Mean   :3.328e-03  
 3rd Qu.:173.04   3rd Qu.:5.131e-03  
 Max.   :248.08   Max.   :5.133e-03

Two other options in this case:

1. Use attach() to place the data frame 'sp' in the current search path.
Now you do not need to explicitly use the data.frame$column notation.
Then detach is then used to clean up.


2. Use with(), which is the preferred notation when dealing with data

with(sp, density(sp))

To avoid your own confusion in the future, it would be better to not
name the data frame with the same name as a vector. It also helps when
others may need to review your code.

See ?with and ?attach for more information.

Reading through "An Introduction to R" which is part of the default
documentation set would be helpful to you in better understanding data
types and dealing with data frame structures.

I see that Prof. Ripley has also replied regarding the nature of
truehist(), so that helps to clear up that mystery.... :-)


Marc Schwartz

More information about the R-help mailing list