[R] Characters and Numeric Values in One Matrix

Gavin Simpson gavin.simpson at ucl.ac.uk
Tue Jul 8 11:32:07 CEST 2003


Hi Roland,

Try the following

 > names <- c("Marge", "Lisa", "Homer", "Bart", "Maggie")
 > ages <- c(38,10,41,8,1)
 > simpsons <- data.frame(I(names), ages)
 > simpsons
    names ages
1  Marge   38
2   Lisa   10
3  Homer   41
4   Bart    8
5 Maggie    1
 > str(simpsons)
`data.frame':   5 obs. of  2 variables:
  $ names:Class 'AsIs'  chr [1:5] "Marge" "Lisa" "Homer" "Bart" ...
  $ ages : num  38 10 41 8 1

Note the use of I() to protect names from the implicit conversion from 
character to factor that data.frame() does.

See ?data.frame for more.

HTH

Gav

Rau, Roland wrote:

> Dear R-Users,
> 
> I want to ask a question for a colleague of mine. He wants to put a
> character vector and a numeric vector into one matrix and still have the old
> character and numeric type for the respective columns.
> Unfortunately, I am just starting using R and I could not help him.
> Is there an easy and straightforward way to do this in R?
> 	
> Maybe a little example facilitates understanding our problem:
> names <- c("Marge", "Lisa", "Homer", "Bart", "Maggie")
> ages <- c(38,10,41,8,1)
> Now he wants to have 2 columns in a matrix which should look like this:
> "Marge"     38
> "Lisa"      10
> "Homer"     41
> "Bart"       8
> "Maggie"     1
> 
> I thought about using either:
> family1 <- matrix(c(names, ages), ncol=2, byrow=FALSE)
> or
> family2 <- data.frame(names,ages)
> but this simply transformed either the numeric into character values
> (family1) or the character values into factor levels (family2)
> Anyone here who can give us some advice on this?
> 
> We are using R 1.7.0 on Windows NT.
> 
> Thanks,
> Roland
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> 
> 

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Gavin Simpson                     [T] +44 (0)20 7679 5522
ENSIS Research Fellow             [F] +44 (0)20 7679 7565
ENSIS Ltd. & ECRC                 [E] gavin.simpson at ucl.ac.uk
UCL Department of Geography       [W] http://www.ucl.ac.uk/~ucfagls/cv/
26 Bedford Way                    [W] http://www.ucl.ac.uk/~ucfagls/
London.  WC1H 0AP.
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%




More information about the R-help mailing list