[R] reshape a dataset

Jorge I Velez jorgeivanvelez at gmail.com
Fri Aug 15 11:37:49 CEST 2014


Dear Sohail,

Using Jim's data set skdat, two more options would be

# first option
d <- with(skdat, table(ID, lettertag))
names <- colnames(d)
d <- c(list(rownames(d)), lapply(1:ncol(d), function(i) as.numeric(d[,i])))
names(d) <- c('ID', names)
d

# second option
d <- with(skdat, table(ID, lettertag))
res <- c(list(rownames(d)), sapply(apply(d, 2, list), "[", 1))
names(res)[1] <- "ID"
res

HTH,
Jorge.-



On Fri, Aug 15, 2014 at 7:19 PM, Jim Lemon <jim at bitwrit.com.au> wrote:

> On Thu, 14 Aug 2014 06:08:51 PM Sohail Khan wrote:
> > Hi
> > I have data set as follows:
> >   A 92315  A 35018  A 56710  B 52700  B 92315  B 15135  C 35018  C
> 52700
> > I would like to transform this data set into:
> >   ID 92315 35018 56710 52700 15135  A 1 1 1 0 0  B 1 0 0 1 1  C 0 1 0
> 1 0
> > I looked into reshape package to no avail.
> > I would appreciate any suggestions.
> >
> > -Sohail
> >
> Hi Sohail,
> You are doing a bit more than reshaping. This may get you there:
>
> skdat<-read.table(text="A 92315
> A 35018
> A 56710
> B 52700
> B 92315
> B 15135
> C 35018
> C 52700",stringsAsFactors=FALSE)
> names(skdat)<-c("lettertag","ID")
> ID<-unique(skdat$ID)
> lettertags<-unique(skdat$lettertag)
> newskdat<-list(ID)
> for(i in 1:length(lettertags))
>  newskdat[[i+1]]<-
>   as.numeric(ID %in% skdat$ID[skdat$lettertag==lettertags[i]])
> names(newskdat)<-c("ID",lettertags)
>
> I'm assuming that you don't really want your answer as a single string.
>
> Jim
>
> ______________________________________________
> 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list