[R] Rows to Column

David Carlson dcarlson at tamu.edu
Mon Dec 16 15:53:36 CET 2013


Also
> tbl <- xtabs(val~id+cat, dat1)
> tbl
   cat
id  A B C D
  1 2 0 4 0
  3 0 1 0 0
  5 2 0 0 0
  6 3 5 2 0
  8 0 5 0 2
  9 0 0 0 3

To get your column names
> dimnames(tbl)$cat <- paste0("cat", dimnames(tbl)$cat)
> tbl
   cat
id  catA catB catC catD
  1    2    0    4    0
  3    0    1    0    0
  5    2    0    0    0
  6    3    5    2    0
  8    0    5    0    2

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352



-----Original Message-----
From: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org] On Behalf Of arun
Sent: Sunday, December 15, 2013 7:49 PM
To: r-help at r-project.org
Cc: marcos.takahashi
Subject: Re: [R] Rows to Column

Hi,
Try:
dat1 <- read.table(text="id cat val
1  A  2
1  C  4
3  B  1
5  A  2
6  A  3
6  B  5
6  C  2
8  B  5
8  D  2
9  D  3",sep="",header=TRUE,stringsAsFactors=FALSE)


library(reshape2)
 res1 <- dcast(dat1,id~cat,value.var="val",fill=0)
colnames(res1)[-1] <- paste0("cat",colnames(res1)[-1])


#or
 xtabs(val~id+cat,data=dat1)
A.K.


On Sunday, December 15, 2013 8:38 PM, marcos.takahashi
<marcos.takahashi at mobly.com.br> wrote:
Hi all,
I'm kinda new in R programming and I need some help preparing a
database to
run logistic regression.

I have data in a tuple form:

*id cat val*
1   A   2
1   C   4
3   B   1
5   A   2
6   A   3
6   B   5
6   C   2
8   B   5
8   D   2
9   D   3

and would like to have it like:

*id    catA    catB    catC    catD*
1    2    0      4      0
3    0    1      0      0
5    2    0      0      0
6    3    5      2      0
8    0    5      0      2
9    0    0      0      3

Could someone help me?
I have already tried table function, but it doesn't return row
and column
names.



--
View this message in context:
http://r.789695.n4.nabble.com/Rows-to-Column-tp4682245.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help at r-project.org 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.


______________________________________________
R-help at r-project.org 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.



More information about the R-help mailing list