It sounds like you should explore dcast
from "reshape2":
library(reshape2)
dcast(DF, PartyCountry + PartyYear ~ PartyCode, value.var="PartyCode")
# Aggregation function missing: defaulting to length
# PartyCountry PartyYear 20 21 22
# 1 CHN 1999 1 0 0
# 2 CHN 2000 2 0 0
# 3 CHN 2001 0 0 1
# 4 GER 1999 3 0 0
# 5 USA 2000 0 2 0
# 6 USA 2001 2 0 2
Here, we've just "counted" (using length
as the aggregation variable), but you can also use different functions (for example, sum
or mean
) if they were more meaningful.
Generally, "collapsing" data suggests looking at one of the many "aggregation" functions in R. Then, transforming from the "long" format that you start with to the "wide" format you want to end up with usually suggests looking at one of the "reshaping" functions.