######################## # R Course WS 2018-19 ######################## # Solutions to exercise sheet 8 - Algorithmics in R (continued) # Updated by Sonja 20/02/2018 ### Exercise 1 # Definition of the function myfact<- function(data){ y <-c() for (i in 1:dim(data)[2]){ if (is.factor(data[,i]) == TRUE){ y<-c(y, names(data)[i]) } } return(y) } # Test myfact(heartbeats) ht2 <- heartbeats ht2$wghtcls <- as.factor(ht2$wghtcls) myfact(ht2) ### Exercise 2 ## Help on the function is.na() ?is.na # Answers TRUE if NA and FALSE if not NA ## Writing the function which.na() which.na <- function(x) { return (which(is.na(x))) } ## Writing the function rm.na() rm.na <- function(x) { return (x[!is.na(x)]) } ### Exercise 3 ## First version of the function se <- function(x) { return(sd(x)/sqrt(length(x))) } # Test se(c(3, 5, "a", 7)) # The function produces warning and NA se(c(3, NA, 8, 2)) # The function produces NA ## Improved function se <- function(x, na.rm = FALSE) { if (is.numeric(x) != TRUE) { warning("Argument is not numeric: returning NA") return(NA) } if (na.rm == TRUE) { x<-x[is.na(x) == FALSE] } return(sd(x)/sqrt(length(x))) } # Test se(c(3, 5, "a", 7)) # Warning message: # In se(c(3, 5, "a", 7)) : Argument is not numeric: returning NA se(c(3, NA, 8, 2), na.rm = TRUE) # [1] 1.855921