我正在考虑如何重塑这样的数据框:
id type points times
1 A 3 1
2 B 3 2
3 A 3 3
4 B 2 4
5 A 1 5
对此:
points A B
1 5 0
2 0 4
3 4 2
所以,我想让点和类型成为列,并计算所有类型中一个点的外观总数。
使用tidyverse
,您可以:
df %>%
group_by(type, points) %>%
summarise(sum = sum(times)) %>%
spread(type, sum, fill = 0)
points A B
<int> <dbl> <dbl>
1 1 5 0
2 2 0 4
3 3 4 2
你可以使用dcast
的reshape2
reshape2::dcast(dat[-1], points ~ type, fill = 0, fun.aggregate = sum)
# points A B
#1 1 5 0
#2 2 0 4
#3 3 4 2
或者没有外部包你可以使用xtabs
xtabs(times ~ points + type, data = dat)
# type
#points A B
# 1 5 0
# 2 0 4
# 3 4 2