[R] Pivot
arun
smartpink111 at yahoo.com
Tue Jan 29 15:12:21 CET 2013
HI,
You could try:
dat1<-read.table(text="
X Z
x1 102
x2 102
x2 102
x2 77
x3 23
",sep="",header=T,stringsAsFactors=F)
res1<-tapply(dat1[,1],list(dat1[,1],dat1[,2]),length)
res1[apply(res1,2,function(x) is.na(x))]<-0
colnames(res1)<-paste("Z.",colnames(res1),sep="")
res1
# Z.23 Z.77 Z.102
#x1 0 0 1
#x2 0 1 2
#x3 1 0 0
#or
library(reshape2)
res2<- dcast(dat1,X~Z,length,value.var="Z")
colnames(res2)<-paste("Z.",colnames(res2),sep="")
----- Original Message -----
From: farnoosh sheikhi <farnoosh_81 at yahoo.com>
To: "r-help at R-project.org" <r-help at r-project.org>
Cc:
Sent: Monday, January 28, 2013 6:48 PM
Subject: [R] Pivot
Hi,
I have a data set as follow:
X Z
x1 102
x2 102
x2 102
x2 77
x3 23
I need to pivot this data as follows and assign the values based on frequency of column Z:
X Z.102 Z.77 Z.23
x1 1 0 0
x2 21 0
x3 00 1
Thanks.
Best,Farnoosh Sheikhi
[[alternative HTML version deleted]]
______________________________________________
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