Search code examples
rsummary

How to build a summary data frame


I have a data set looks like this:

enter image description here

and I would like to get a summary data set that will looks like this: enter image description here

what should i do? Thanks. The sample.data can be build through following codes:

ID<- c("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18")
Group<-c("A","B","C","D","D","D","A","B","D","C","B","D","A","A","C","B","B","B")
Color<-c("Green","Yellow","Red","Red","Red","Yellow","Green","Green","Yellow","Red","Red","Yellow","Yellow","Yellow","Green","Red","Red","Green")
Realy_Love<-c("Y","N","Y","Y","N","N","Y","Y","Y","N","N","Y","N","Y","N","Y","N","Y")
Sample.data <- data.frame(ID, Group, Color, Realy_Love)

Solution

  • You can use dplyr and group by the following items:

    Sample.data %>%
      group_by(Group, Color, Realy_Love) %>%
      summarise(Obs = n())
    
    # Group Color  Realy_Love   Obs
    # <chr> <chr>  <chr>      <int>
    # 1 A     Green  Y              2
    # 2 A     Yellow N              1
    # 3 A     Yellow Y              1
    # 4 B     Green  Y              2
    # 5 B     Red    N              2
    # 6 B     Red    Y              1
    # 7 B     Yellow N              1
    # 8 C     Green  N              1
    # 9 C     Red    N              1
    # 10 C     Red    Y              1
    # 11 D     Red    N              1
    # 12 D     Red    Y              1
    # 13 D     Yellow N              1
    # 14 D     Yellow Y              2