The following function satisfies the conditions listed below:
# Creating test variables
x <- c(12, 20, 18, 32, 15, 20) # Numeric
y <- c("M", "M", "F", "F", "M", "M", "M", "F") # Character
# Creating aforementioned function
SummaryStat <- function(x){
if (class(x) == "numeric") {
Summ <- summary(x)
StandardDev <- sd(x)
Summary <- c(Summ, "Std.Dev." = StandardDev)
return(Summary)
} else {
Tab <- table(x)
return(Tab)
}
}
# Testing function with test variables
SummaryStat(x)
## Min. 1st Qu. Median Mean 3rd Qu. Max. Std.Dev.
## 12.000000 15.750000 19.000000 19.500000 20.000000 32.000000 6.862944
SummaryStat(y)
## x
## F M
## 3 5
The following function satisfies the conditions listed below:
# Character vector that we will use to test our function
Names1 <- names(mtcars)
Names1
## [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear"
## [11] "carb"
# Creating the function
UpperCase1 <- function(x) {
if(class(x) == "character"){
Fl <- toupper(substr(x, 1, 1))
Word <- tolower(substr(x, 2, nchar(x)))
paste0(Fl, Word, collapse = NULL)
} else {
print("Only applicable to character vectors.")
}
}
# Testing the function on the test vector
UpperCase1(Names1)
## [1] "Mpg" "Cyl" "Disp" "Hp" "Drat" "Wt" "Qsec" "Vs" "Am" "Gear"
## [11] "Carb"