[R] character -> list

Gabor Grothendieck ggrothendieck at myway.com
Fri Mar 19 02:46:16 CET 2004


It would be helpful if you were more explicit on what you mean
by not successful.

Is the problem that:
1. you can't get aggregate to work with character data or 
2. you want to convert the numeric column to numbers or
3. you want to have a structure that has both numbers and character
columns

Also, I am not sure if you actually want the characters or if you
want the character columns converted to factors or, if applicable
to numbers.

In case 1, it actually does work:

> aggregate(x[,-2], list(x[,2]), length)
  Group.1 type value
1       b    2     2
2       c    1     1

In case 2, use as.numeric:

> aggregate(list(value=as.numeric(x[,3])),list(group=x[,2]), mean)
  group value
1     b   1.5
2     c   3.0

In case 3, create a data frame:
x.df <- data.frame(type = I(x[,1]), group = I(x[,2]), value = as.numeric(x[,3]))

If you want the character columns converted to factors then get
rid of the I's.


Date:   19 Mar 2004 00:47:38 +0100 
From:   David Andel <andel at ifi.unizh.ch>
To:   <R-help at stat.math.ethz.ch> 
Subject:   [R] character - > list 

 
Hi

I have a matrix of type "character" (strangly) and am trying to apply 
the function "aggregate" to it, but unfortunately without success.
It seems to me that aggregate would work, if I only could get rid of the 
quotation marks around each item.

So for a very simple example which looks as my actual data look (of 
course here I put the quotation marks on purpose, but I have no idea 
where they come from in my actual data):

> x <- matrix(c("a","b","1","a","c","3","b","b","2"), nr=3, byrow=T, 
dimnames=list(1:3, c("type","group","value")))
> x
type group value
1 "a" "b" "1"
2 "a" "c" "3"
3 "b" "b" "2"

I can't access the columns the way I think would be necessary for 
aggregate to work:
> x$type
NULL

And this seems to be the problem:
> typeof(x)
[1] "character"

I think I would need to have type "list" to be able to apply "aggregate".

How can I accomplish this?

Thanks,
David




More information about the R-help mailing list