[R] Rows to Column

arun smartpink111 at yahoo.com
Mon Dec 16 02:49:25 CET 2013


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.




More information about the R-help mailing list