library(learnr)
library(testwhat)
knitr::opts_chunk$set(echo = FALSE, message=FALSE)
tutorial_options(exercise.timelimit = 60, exercise.checker=testwhat::testwhat_learnr)

require(tidyverse)

set.seed(123)
gender_age <-paste0(rep(c("F","M"), each=3), rep(c("0-14","15-44","45+")))
df1 <- tibble(GenderAge=sample(gender_age, 33, replace=TRUE), Pre=rnorm(33, 10, 2), Post=rnorm(33, 15, 1))

mammals <- read_csv("http://personal.strath.ac.uk/kate.pyper/HSM_Tidyverse/Data/tidyr/Mammals.csv")
set.seed(123)
gender_age <-paste0(rep(c("F","M"), each=3), rep(c("0-14","15-44","45+")))
df1 <- tibble(GenderAge=sample(gender_age, 33, replace=TRUE), Pre=rnorm(33, 10, 2), Post=rnorm(33, 15, 1))

Exercise 1

The data frame df1 contains information on the levels of a vitamin pre- and post- treatment. The data contain information on Gender (denoted "M" or "F") and age group. These are contained in a single column. As shown below:

df1

Use the separate() function to get this data frame into an appropriate form, with appropriately named columns

# Separate Gender and Age
df1 %>% separate(GenderAge, c("Gender","Age"), 1)
ex() %>% {
  check_error(.)
  check_function(., "separate") %>% {
    check_arg(., "col") %>% check_equal(., eval=FALSE, eq_fun=function(x,y) {stringr::str_extract(x, "[[:alpha:]]+" )==stringr::str_extract(y, "[[:alpha:]]+" )})
    check_arg(., "into") %>% check_equal(., eq_fun=function(x,y){all((tolower(x)==tolower(y))|(tolower(x)==tolower(y)[2:1]))})
    check_arg(., "sep") %>% check_equal(.)
  }
}

Exercise 2

mammals <- read_csv("http://personal.strath.ac.uk/kate.pyper/HSM_Tidyverse/Data/tidyr/Mammals.csv")

A data frame called mammals has been made. It contains a column called orderGenus that contains the animal order and its genus separated by a colon :. These two pieces of information should be separated into two columns.

# Separate Order and Genus
mammals %>% separate(orderGenus, c("Order","Genus"), ":")
ex() %>% {
  check_error(.)
  check_function(., "separate") %>% {
    check_arg(., "col") %>% check_equal(., eval=FALSE, eq_fun=function(x,y) {stringr::str_extract(x, "[[:alpha:]]+" )==stringr::str_extract(y, "[[:alpha:]]+" )})
    check_arg(., "into") %>% check_equal(., eq_fun=function(x,y){all((tolower(x)==tolower(y))|(tolower(x)==tolower(y)[2:1]))})
    check_arg(., "sep") %>% check_equal(.)
  }
}


kate-pyper/MM916ProgrammingExercises documentation built on Oct. 15, 2020, 10:40 p.m.