0

I have tried several times, but the function group_by returns only one value, and the function 'ddply' in the plyr package returns several values that are more suited to what I intended.

Check my simple code

library(MASS)
library(dplyr)
library(plyr)

Cars93$cnt <- rep(1,norw(Cars93))

#using group_by function 
Cars93 %>% group_by(Type) %>% summarise( n = sum(cnt))

#group_by returns 
#  n
#1 6

#using ddply function 
ddply (Cars93,.(Type), summarise, n = sum(cnt) )

#ddply returns

#     Type  n
#1 Compact 16
#2   Large 11
#3 Midsize 22
#4   Small 21
#5  Sporty 14
#6     Van  9

I want the group_by function to return exactly the same result as the ddply function.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
timothy jeong
  • 97
  • 1
  • 12

1 Answers1

0

Another method you can use is the function tally which counts by each group, saving the need for creating a new column.

Cars93 %>% 
  group_by(Type) %>% 
  tally()

# A tibble: 6 x 2
  Type        n
  <fct>   <int>
1 Compact    16
2 Large      11
3 Midsize    22
4 Small      21
5 Sporty     14
6 Van         9
Aidan
  • 30
  • 8