[R] changing the form of a list

Thomas Lumley tlumley at u.washington.edu
Mon Apr 8 17:37:10 CEST 2002


On Mon, 8 Apr 2002, jimi adams wrote:

> i have a 2 x n matrix that is a paired list of connections, i am working
> with that looks something like:
> 1 2
> 1 3
> 1 5
> 2 1
> 2 3
> 3 1
> 3 2
> 4 5
> 5 1
> 5 4
> for later operations it would be helpful if i could change this into the
> form of:
> 1  2 3 5
> 2  1 3
> 3  1 2
> 4  5
> 5  1 4
> the initial list is randomly generated and the max number of times that any
> one number can appear is previoulsy defined by a limiting function (which is
> variable depending on the numbers involved)
> is there a clean way to change the form of that list?

Suppose the matrix is actually a data.frame (if it isn't, use
as.data.frame) called df with columns called i and x

tapply(df$x, df$i, c)

> df
   i  x
1  1  1
2  2  2
3  3  3
4  3  4
5  4  5
6  2  6
7  1  7
8  3  8
9  4  9
10 3 10
>  tapply(df$x,df$i,c)
$"1"
[1] 1 7

$"2"
[1] 2 6

$"3"
[1]  3  4  8 10

$"4"
[1] 5 9

Or by()

> by(df, df$i, function(subset) subset$x)
df$i: 1
[1] 1 7
------------------------------------------------------------
df$i: 2
[1] 2 6
------------------------------------------------------------
df$i: 3
[1]  3  4  8 10
------------------------------------------------------------
df$i: 4
[1] 5 9

Or you might want to leave the data in its current form and use tapply()
or by() to do whatever it is you want to do with it.

	-thomas




-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list