Philip John
Philip John

Reputation: 5555

R count two column values and obtain the result in a tabular form

I have a dataset as shown

Num              Day
1111             Thursday
2222             Thursday
3333             Thursday
1111             Monday
1111             Tuesday
1111             Wednesday
1111             Friday
1111             Saturday
1111             Sunday
2222             Thursday

I need to get the count of the each Num for the corresponding Day. I have used as.data.frame(table(data$Num,data$Day)) and got the output like in the following format.

Num              Day              Freq
1111             Thursday         1
1111             Monday           1
1111             Tuesday          1
1111             Wednesday        1
1111             Friday           1
1111             Saturday         1
1111             Sunday           1
.
.
2222             Thursday         2
.
.
3333             Thursday         1
.
.

For better visualising I need the output like the following.

      Sunday  Monday  Tuesday  Wednesday  Thursday  Friday  Saturday
1111  1       1       1        1          1         1       1
2222  0       0       0        0          2         0       0
3333  0       0       0        0          1         0       0 

Is there a way to do this?

Upvotes: 4

Views: 75

Answers (1)

Mamoun Benghezal
Mamoun Benghezal

Reputation: 5314

try this

table(data)
      Day
Num    Friday Monday Saturday Sunday Thursday Tuesday Wednesday
  1111      1      1        1      1        1       1         1
  2222      0      0        0      0        2       0         0
  3333      0      0        0      0        1       0         0

Upvotes: 4

Related Questions