[R] aggregate counting variable factors
Frank Schwidom
schwidom at gmx.net
Thu Sep 17 18:01:06 CEST 2015
Hi
res <- sapply( df1[ , -1], function( x) table(x)[as.character( 0:5)])
rownames( res) <- paste( sep='', 'result', 0:5)
res[ is.na( res)] <- 0
res
item1 item2 item3 item4 item5
result0 1 0 1 1 0
result1 1 2 0 0 0
result2 1 2 1 1 0
result3 0 0 1 2 0
result4 0 0 1 0 0
result5 1 0 0 0 4
t( res)
result0 result1 result2 result3 result4 result5
item1 1 1 1 0 0 1
item2 0 2 2 0 0 0
item3 1 0 1 1 1 0
item4 1 0 1 2 0 0
item5 0 0 0 0 0 4
Regards
On Wed, Sep 16, 2015 at 10:43:16PM +0200, Kai Mx wrote:
> Hi everybody,
>
> >From a questionnaire, I have a dataset like this one with some 40 items:
>
> df1 <- data.frame(subject=c('user1','user2', 'user3', 'user4'),
> item1=c(0,1,2,5), item2=c(1,2,1,2), item3=c(2,3,4,0), item4=c(0,3,3,2),
> item5=c(5,5,5,5))
>
> Users can choose an answer from 0 to 5 for each item.
>
> Now I want to reshape the dataset to have the items in rows and the count
> of each of the result factors in columns:
>
> result <- data.frame (item=c("item1", "item2", "item3", "item4", "item5"),
> result0=c(1,0,1,1,0), result1=c(1,2,0,0,0), result2=c(1,2,1,1,0),
> result3=c(0,0,1,2,0), result4=c(0,0,1,0,0), result5=c(1,0,0,0,4))
>
> I have been fiddling around with melt/plyr, but haven't been able to figure
> it out. What's the most elegant way to do this (preferably without typing
> in all the item names).
>
> Thanks so much!
>
> Best,
>
> Kai
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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