monkey
monkey

Reputation: 1597

How to Summarise And Group in R

New to R, and trying to create some summaries of data.

test_data <- tibble(x=1:10,y=11:20, room=c("a","b","a","b","a","b","a","b","a","b"), colour=c("red","blue","green","black","red","red","blue","green","black","red"))
summary_data <- test_data %>%
  filter(room != "NA") %>%
  group_by(room) %>%
  summarise_all(funs(sum(complete.cases(.)))) %>%
  rename_all(~paste0("risk_",colnames(summary_data)))

Gives:

> summary_data
# A tibble: 2 x 4
  risk_room risk_x risk_y risk_colour
  <chr>      <int>  <int>       <int>
1 a              5      5           5
2 b              5      5           5

Which is not at all what I want! What I'm trying for is :

enter image description here

Or

enter image description here

Upvotes: 0

Views: 70

Answers (1)

Henry Cyranka
Henry Cyranka

Reputation: 3060

Using janitor and tidyverse

library(tidyverse)
library(janitor)
test_data <- tibble(x=1:10,y=11:20, room=c("a","b","a","b","a","b","a","b","a","b"), colour=c("red","blue","green","black","red","red","blue","green","black","red"))

test_data %>%
    group_by(room, colour) %>%
    tally() %>% 
    spread(colour, n) %>%
    adorn_totals("col", name = "Count") %>%
    adorn_totals("row",name = "Total")

Upvotes: 4

Related Questions