[R] R Data Manipulation - Transposing Data by a Given Column, Like User_ID
Peter Ehlers
ehlers at ucalgary.ca
Fri Feb 4 04:05:04 CET 2011
On 2011-02-03 14:09, Dennis Murphy wrote:
> Hi:
>
> This also works, except that the result is of class 'table':
>
> xtabs(COUNTS ~ USER_ID + SITE, data = RAW)
> SITE
> USER_ID SITE1 SITE2 SITE3
> 1 10 13 22
> 2 10 12 12
> 3 13 44 0
> 4 0 0 99
>
> If you need a data frame, then the earlier responses apply.
Agreed. But just for fun, since this is R:
z <- xtabs(COUNTS ~ USER_ID + SITE, data = RAW)
d <- as.data.frame(unclass(z))
That'll lose the USER_ID variable; if that's needed:
d <- as.data.frame(cbind(USER_ID=row.names(z), unclass(z)))
Peter Ehlers
>
> HTH,
> Dennis
>
> On Thu, Feb 3, 2011 at 11:41 AM, Mike Schumacher
> <mike.schumacher at gmail.com>wrote:
>
>> Hello,
>>
>> I'd like to transpose data to create an analysis-friendly dataframe. See
>> below for an example, I was unable to use t(x) and I couldn't find a
>> function with options like PROC TRANSPOSE in SAS.
>>
>> The ideal solution handles variable quantities of SITE - but beggars can't
>> be choosers. :-)
>>
>> Thank you in advance,
>>
>> Mike
>>
>> ## INPUT DATA
>> USER_ID<-c(1,1,1,2,2,2,3,3,4)
>> SITE
>>
>> <-c("SITE1","SITE2","SITE3","SITE1","SITE2","SITE3","SITE1","SITE2","SITE3")
>> COUNTS<-c(10,13,22,10,12,12,13,44,99)
>>
>> RAW<-data.frame(USER_ID,SITE,COUNTS)
>> RAW
>>
>> #ANSWER SHOULD LOOK LIKE
>> a<-c(1,2,3,4)
>> b<-c(10,10,13,0)
>> c<-c(13,12,44,0)
>> d<-c(22,12,0,99)
>>
>> RESULT<-data.frame(a,b,c,d)
>> names(RESULT)<-c("USER_ID","SITE1","SITE2","SITE3")
>> RESULT
>>
>>
>>
>>
>> --
>> Michael Schumacher
>> mike.schumacher at gmail.com
>>
>> [[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.
>>
>
> [[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