RunninigPig
RunninigPig

Reputation: 25

R reshape a data frame to get the total number of appearance of an observation

I am thinking about how to reshape a data frame like this:

id type points times
1   A    3       1
2   B    3       2
3   A    3       3
4   B    2       4
5   A    1       5

to this :

points   A    B
1        5    0
2        0    4
3        4    2

So, I want to make the points and types be the column, and count the total number of appearance of a point in all types.

Upvotes: 2

Views: 49

Answers (2)

markus
markus

Reputation: 26343

You might use dcast from 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

Or without external packages you can use xtabs

xtabs(times ~ points + type, data = dat)
#      type
#points A B
#     1 5 0
#     2 0 4
#     3 4 2

Upvotes: 2

tmfmnk
tmfmnk

Reputation: 39858

With tidyverse, you can do:

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

Upvotes: 1

Related Questions