f <- function() {
# this is an empty function with no arguments or body code
}
class(f)
## [1] "function"
f()
## NULL
f <- function(){
print("Hello, world!")
}
f()
## [1] "Hello, world!"
f <- function(friend){
cat("Hello", friend, "!\n")
}
f("Mike")
## Hello Mike !
f(50)
## Hello 50 !
f <- function(friend){
if(is.character(friend)) {
cat(paste0("Hello ", friend, "!\n"))
}
else {
warning("You didnt not enter a character string!")
}
}
f("Mike")
## Hello Mike!
f(50)
## Warning in f(50): You didnt not enter a character string!
f <- function(friend = "my friend"){
if(is.character(friend)) {
cat(paste0("Hello ", friend, "!\n"))
}
else {
stop("You didnt not enter a character string!")
}
}
f()
## Hello my friend!
f("Mike")
## Hello Mike!
convertTemp <- function(degrees, type = "F"){v
`%!in` <- Negate(`%in%`)
if(type %!in% c("F", "C", "f", "c")){
warning('Enter "C" for Celsius or "F" (or blank for Fahrenheit)')
}
if(type == "F" | type == "f"){
result <- round((degrees - 32) * (5/9), 1)
cat(paste0(degrees,
" Fahrenheit is ", result, "Celsius\n"))
#return(result)
} else if ( type == "C" | type == "c") {
result <- round((degrees * 9/5)+ 32, 1)
cat(paste0(degrees,
" Celcius is ", result, " Farhrenheit=\n"))
}
}
find_mode <- function(x){
u <- unique(x)
tab <- tabulate(match(x, u))
u[tab == max(tab)]
}
find_mode(c(0,0,0,1,1,1,4,4,7,10))
## [1] 0 1
#anonymous function
f <- function(friend){
cat("hello", friend, "!\n")
}
f("Mike")
## hello Mike !
(function (x) {cat("Hello", x, "!\n")}) ("Mike")
## Hello Mike !
weight <- readline(prompt = "Enter Your Weight(in pounds): ")
## Enter Your Weight(in pounds):
height <- readline(prompt = "Enter Your Height(in inches): ")
## Enter Your Height(in inches):
#convert to numeric
weight <- as.numeric(weight)
height <- as.numeric(height)
bmi <- weight / (height*height) *703
print(paste("Your BMI is:", bmi))
## [1] "Your BMI is: NA"