# [R] Reshaping a table

David L Carlson dcarlson at tamu.edu
Mon Apr 8 18:16:56 CEST 2013

```If you are starting with a table rather than a data frame, try this

> # Convert Arun's data.frame, dat1, to a table, dat2
> dat2 <- as.table(as.matrix(data.frame(dat1[,2:3], row.names=dat1[,1])))
> # convert dat2 to form requested
> dat3 <- data.frame(dat2)
> dat4 <- dat3[rep(1:nrow(dat3), dat3\$Freq),1:2]
> colnames(dat4) <- c("X", "Y")
> rownames(dat4) <- NULL
> dat4
X  Y
1 0.1 Y1
2 0.1 Y1
3 0.1 Y1
4 0.2 Y1
5 0.2 Y1
6 0.1 Y2
7 0.1 Y2
8 0.2 Y2

X and Y are factors. If you want them to be character vectors add:

> dat4 <- data.frame(sapply(dat4, as.character), stringsAsFactors=FALSE)

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of arun
> Sent: Monday, April 08, 2013 7:41 AM
> To: IOANNA
> Cc: R help
> Subject: Re: [R] Reshaping a table
>
> Hi,
> Try this:
> X      Y1    Y2
>
> 0.1  3      2
>
> 0.2  2      1
>
>
>  res<-do.call(rbind,lapply(split(dat1,seq_len(nrow(dat1))),function(x)
> {Y=rep(colnames(x)[-1],x[-1]); X=rep(x[,1],length(Y));
> data.frame(X,Y,stringsAsFactors=FALSE)}))
>  row.names(res)<- 1:nrow(res)
>  res
> #    X  Y
> #1 0.1 Y1
> #2 0.1 Y1
> #3 0.1 Y1
> #4 0.1 Y2
> #5 0.1 Y2
> #6 0.2 Y1
> #7 0.2 Y1
> #8 0.2 Y2
> A.K.
>
>
>
> ----- Original Message -----
> From: IOANNA <ii54250 at msn.com>
> To: 'r-help-r-project.org' <r-help at r-project.org>
> Cc:
> Sent: Monday, April 8, 2013 8:09 AM
> Subject: [R] Reshaping a table
>
> Hello all,
>
>
>
> I have data in the form of a table:
>
>
>
> X      Y1    Y2
>
> 0.1   3       2
>
> 0.2   2       1
>
>
>
> And I would like to transform in the form:
>
>
>
> X     Y
>
> 0.1   Y1
>
> 0.1   Y1
>
> 0.1   Y1
>
> 0.1   Y2
>
> 0.1   Y2
>
> 0.2  Y1
>
> 0.2  Y1
>
> 0.2  Y2
>
>
>
> Any ideas how?
>
>
>
>
> IOanna
>
>
>
>
>
>
>
>
>     [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help