[R] Creating a data.frame

Chuck Cleland ccleland at optonline.net
Thu Feb 14 00:08:28 CET 2008


On 2/13/2008 5:17 PM, Joe Trubisz wrote:
> OK...newbie question here.
> Either I'm reading the docs wrong, or I'm totally confused.
> 
> Given the following:
> 
> x<-c("aaa","bbb","ccc")
> y<-rep(0,3)
> z<-rep(0,3)
> 
> is.character(x)
> [1] TRUE
> 
> is.numeric(y)
> [1] TRUE
> 
> Now...I want to create a data frame, but keep the data types.
> In reading the docs, I assume you do it this way:
> 
> d<-data.frame(cbind(x=I(x),y=y,z=z)
> 
> But, when I do str(d), I get the following:
> 
> 'data.frame':	3 obs. of  3 variables:
>   $ x: Factor w/ 3 levels "aaa","bbb","ccc": 1 2 3
>   $ y: Factor w/ 1 level "0": 1 1 1
>   $ z: Factor w/ 1 level "0": 1 1 1
> 
> I thought the I() prevents character from becoming factors, right?
> Secondly, how do I force y and z in the data frame to become numeric?

   Don't use cbind() inside of data.frame().  Using cbind() coerces the 
variables into a matrix where all variables share a common type.  I 
think you want this:

d <- data.frame(x=I(x), y=y, z=z)

> Thanks in advance
> Joe
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list