[R] format: from list to data frame

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Sat Mar 13 17:58:08 CET 2010


On Sat, Mar 13, 2010 at 4:46 PM, Javier <j.perez-barberia at macaulay.ac.uk> wrote:
>
> Dear users,
>
> Is anyone out there on a Saturday to answer this easy question?
>
> I have the "yo" object data in a "list" format:
>
>> str(yo)
>  num [1:259, 1:173] 16.3 NA NA NA NA ...
>  - attr(*, "dimnames")=List of 2
>  ..$ x: chr [1:259] "367319" "367329" "367309" "367339" ...
>  ..$ y: chr [1:173] "780175" "780185" "780195" "780205" ...
>> length(yo)
> [1] 44807
>
> where x is the name of the rows and y the name of the columns (coordinates)
> of a matrix of 44807 values
>
> how can I get a data.frame with these three columns: x, y, values
>
> Many thanks to the Saturday working people.

 Let's try with something a bit smaller. Not sure what you mean by
list format, your thing looks like a matrix:

d=matrix(1:12,ncol=4)
dimnames(d) <- list(letters[1:3],letters[9:12])

- hence:

 > str(d)
 int [1:3, 1:4] 1 2 3 4 5 6 7 8 9 10 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:3] "a" "b" "c"
  ..$ : chr [1:4] "i" "j" "k" "l"
 > length(d)
 [1] 12

If I use 'melt' from the 'reshape' package:

> require(reshape)
> melt(d)
   X1 X2 value
1   a  i     1
2   b  i     2
3   c  i     3
4   a  j     4
5   b  j     5
6   c  j     6
7   a  k     7
8   b  k     8
9   c  k     9
10  a  l    10
11  b  l    11
12  c  l    12

I think I get pretty much what you want. You might need to set the
columns to numeric and maybe change the names.

Barry



More information about the R-help mailing list