[R] dataframe layout

Chuck Cleland ccleland at optonline.net
Wed Mar 14 10:06:58 CET 2007


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

  Here are a couple of different approaches:

df.b <- data.frame(dat = unlist(df.a),
                   lev = rep(names(df.a), each = dim(df.a)[1]))

df.b
   dat lev
a1   1   a
a2   2   a
a3   3   a
b1   4   b
b2   5   b
b3   6   b
c1   7   c
c2   8   c
c3   9   c

library(reshape)
melt(df.a, measure.var = names(df.a), variable_name = "lev")

  lev value
1   a     1
2   a     2
3   a     3
4   b     4
5   b     5
6   b     6
7   c     7
8   c     8
9   c     9

> Thanks.
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list