Reputation: 3271
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
Upvotes: 3
Views: 13327
Reputation: 34537
The shortest solution I could think of only consists of typing a one-letter method.
The transpose function t
also works on dataframes, not just on matrices.
> data = data.frame(a = c(1,2,3), b = c(4,5,6))
> data
a b
1 1 4
2 2 5
3 3 6
> t(data)
[,1] [,2] [,3]
a 1 2 3
b 4 5 6
Documentation can be found here.
Upvotes: 3
Reputation: 93813
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
Upvotes: 4
Reputation: 118799
Here's a data.table
alternative:
require(data.table)
dt <- as.data.table(df) # where df is your original data.frame
out <- dt[CJ(unique(fan_id), unique(category))][,
setattr(as.list(likes), 'names', as.character(category)),
by = fan_id][is.na(C), C := 0L]
# fan_id A B C
# 1: 10702397 1 4 0
# 2: 35003154 1 1 2
Upvotes: 3
Reputation: 9405
> 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
Upvotes: 3