Robust functions

# Define troublesome x and y

x <- c(NA, NA, NA)

y <- c( 1, NA, NA, NA)

both_na <- function(x, y) {

# Add stopifnot() to check length of x and y

stopifnot(length(x)==length(y))

sum(is.na(x) & is.na(y))

}

# Call both_na() on x and y

both_na(x, y)

col_classes <- function(df) {

class_list <- map(df, class)

# Add a check that no element of class_list has length > 1

if (any(map_dbl(class_list, length) > 1)) {

stop("Some columns have more than one class", call. = FALSE)

}

# Use flatten_chr() to return a character vector

flatten_chr(class_list)

}

big_x <- function(df, threshold) {

# Write a check for x not being in df

if(!"x" %in% names(df)){

stop("df must contain variable called x",call.=F)

}

else if("threshold" %in% names(df)){

stop("df must not contain variable called threshold",call.=F)

}

dplyr::filter(df, x > threshold)

}

你可能感兴趣的:(Robust functions)