Re: [R] Creating a data.frame

From: Ted Harding <Ted.Harding_at_manchester.ac.uk>
Date: Wed, 13 Feb 2008 23:24:35 +0000 (GMT)


On 13-Feb-08 22:17:32, 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?
>
> Thanks in advance
> Joe

You don't need to force it! It's not obvious what made you think of using cbind() internally, but it doesn't do what you intended. Simply:

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

#     x y z
# 1 aaa 0 0
# 2 bbb 0 0
# 3 ccc 0 0

  str(d)
# 'data.frame':   3 obs. of  3 variables:
#  $ x:Class 'AsIs'  chr [1:3] "aaa" "bbb" "ccc"
#  $ y: num  0 0 0
#  $ z: num  0 0 0

The trouble was that cbind(x=I(x),y=y,z=z) makes a matrix, and you cannot mix types in a matrix, so this will coerce all the variables to character type. So it's your original way which does the forcing!

Hoping this helps,
Ted.



E-Mail: (Ted Harding) <Ted.Harding_at_manchester.ac.uk> Fax-to-email: +44 (0)870 094 0861
Date: 13-Feb-08                                       Time: 23:24:30
------------------------------ XFMail ------------------------------

______________________________________________
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. Received on Wed 13 Feb 2008 - 23:37:40 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 14 Feb 2008 - 01:30:14 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive