[R] dataframe layout
Gavin Simpson
gavin.simpson at ucl.ac.uk
Wed Mar 14 10:02:00 CET 2007
On Wed, 2007-03-14 at 03:53 -0500, Robert Baer wrote:
> Can someone remind me how to change the columns in df.a into a two column
> df.b that contains one column of data and another column of the original
> column headings as levels.
>
> Example:
> a=1:3
> b=4:6
> c=7:9
> df.a=data.frame(a,b,c)
>
> Should become in df.b:
> dat lev
> 1 a
> 2 a
> 3 a
> 4 b
> 5 b
> 6 b
> 7 c
> 8 c
> 9 c
>
> Thanks.
One option is stack()
> a=1:3
> b=4:6
> c=7:9
> df.a=data.frame(a,b,c)
> df.a
a b c
1 1 4 7
2 2 5 8
3 3 6 9
> stack(df.a)
values ind
1 1 a
2 2 a
3 3 a
4 4 b
5 5 b
6 6 b
7 7 c
8 8 c
9 9 c
> class(stack(df.a))
[1] "data.frame"
HTH
G
--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Gavin Simpson [t] +44 (0)20 7679 0522
ECRC [f] +44 (0)20 7679 0565
UCL Department of Geography
Pearson Building [e] gavin.simpsonATNOSPAMucl.ac.uk
Gower Street
London, UK [w] http://www.ucl.ac.uk/~ucfagls/
WC1E 6BT [w] http://www.freshwaters.org.uk/
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
More information about the R-help
mailing list