Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - data frame switch rows and columns

I have data frame looking like this:

category fan_id likes
A     10702397  1
B     10702397  4
A     35003154  1
B     35003154  1
C     35003154  2 

I'd like to convert it into a following data frame

fan_id   A B C
10702397 1 4 0
35003154 1 1 2

The only way that I can think of is looping over the data frame and constructing another manually but it seems like there has to be a better way.

It seems like I want to the opposite of what was asked here Switch column to row in a data.frame

like image 686
Jakub Bochenski Avatar asked Dec 01 '25 19:12

Jakub Bochenski


2 Answers

Base reshape function method:

dat <- data.frame(
       category=c("A","B","A","B","C"),
       fan_id=c(10702397,10702397,35003154,35003154,35003154),
       likes=c(1,4,1,1,2)
                 )
result <- reshape(dat,idvar="fan_id",timevar="category",direction="wide")
names(result)[2:4] <- gsub("^.*\\.","",names(result)[2:4])
result

    fan_id A B  C
1 10702397 1 4 NA
3 35003154 1 1  2

Bonus xtabs method:

result2 <- as.data.frame.matrix(xtabs(likes ~ fan_id + category, data=dat))

         A B C
10702397 1 4 0
35003154 1 1 2

Exact format with a fix:

data.frame(fan_id=rownames(result2),result2,row.names=NULL)

    fan_id A B C
1 10702397 1 4 0
2 35003154 1 1 2
like image 112
thelatemail Avatar answered Dec 03 '25 13:12

thelatemail


> library(reshape2)
> dat <- data.frame(category=c("A","B","A","B","C"),fan_id=c(10702397,10702397,35003154,35003154,35003154),likes=c(1,4,1,1,2))
> dcast(dat,fan_id~category,fill=0)
Using likes as value column: use value.var to override.
    fan_id A B C
1 10702397 1 4 0
2 35003154 1 1 2
like image 45
David Avatar answered Dec 03 '25 14:12

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!