4  4. Using some built-in functions

4.1 rm(list=ls())

##################################################################.
#
#  TOPICS
#
# - functions: sqrt abs max min ceiling floor sum mean
#              trunc round
#
# - vector arithmetic and recycling rule
#
# - combining vectors with c function
#
# - functions:  c  length  sum   rep  seq  range
#
# - colon operator (e.g.   3:5   5:-3)
#
##################################################################.

# It's recommended to start coding sessions by removing all variables that 
# you may have stored from the last time you've used R. This prevents confusion
# in case you may have a variable from last time.

rm( list=ls() )    

4.2 sqrt()    abs()    NaN    nesting function calls

############################################################.
#
# Intro to functions
#
# Intro to R vectors
#
############################################################.

#-----------------------------------------------------------.
# sqrt function - eg. sqrt(49)                ####
#
# abs function  - eg. abs(-49)                ####
#
# NaN is "not a number" - eg. sqrt(-49)       ####
#
# nesting function calls - eg. sqrt(abs(-49)) ####
#----------------------------------------------------------.

# To take the square-root of a number in R, use the sqrt function
# For example:
sqrt(25)    # get the square root of 25
[1] 5
sqrt(10)    # get the square root of 10
[1] 3.162278
sqrt(-5)    # square roots of negative numbers return NaN (i.e. "not a number")
Warning in sqrt(-5): NaNs produced
[1] NaN
# sqrt is an example of a "function". 
# A function takes some information as input (e.g. 25)
# and returns a value as output, (e.g. 5)
#
# To see R's help page for the sqrt function type the following:
#
# ?sqrt       # show the help page for sqrt     ####

# Some R help pages show information for multiple functions. 
# The help page for sqrt also shows information about the abs function.
#
# abs gives you the absolute value of a number (i.e. the positive version of the number)
abs(2)      # 2
[1] 2
abs(-2)     # 2 
[1] 2
# We can "nest" one function call inside another function call. 
# 
# When we do so the value that is "returned" by the "inner" function call
# is then "passed" to the "outer" function call.
sqrt(-49)   # NaN
Warning in sqrt(-49): NaNs produced
[1] NaN
sqrt(abs(-49))   # 7
[1] 7

4.4 function call

#.......................................................................
# A particular use of a function is known as a "function call"    ####
#.......................................................................

sqrt(100) # this is a function call of the sqrt function
[1] 10
sqrt(64)  # this is a different function call of the sqrt function
[1] 8

4.5 return value

#.......................................................................
# The output of a function is known as the "return value" of the function.   ####
#.......................................................................

sqrt(64)  # The "return value" of this "function call" is 8
[1] 8

4.6 max() min() ceiling() floor() sum()

# Some functions can take more than one argument.
# However, all functions return exactly one item.
# (we will describe an exception to this later).
#
# max and min functions return the maximum and minimum value of all of their arguments. ####
# For example:

max(4,10,2,5)   # four arguments, 4,10,2,5 - one return value, i.e. 10
[1] 10
min(4,10,2,5)   # four arguments, 4,10,2,5 - one return value, i.e. 2
[1] 2
# another example
joesSalary <- 50
suesSalary <- 70
bobsSalary <- 60

# three arguments - joesSalary, suesSalary, bobsSalary
# one return value, i.e. 70

max(joesSalary, suesSalary, bobsSalary)   
[1] 70

4.7 arguments (AKA parameters)

#.......................................................................
# The input values to a function are known as the argument(s) or the parameter(s) of 
# a function. (Some people/books may draw a distinction between the word argument
# and the word parameter but for our purposes they mean the same thing.)
#.......................................................................

# In the following code:
# 36 is an argument (or parameter), i.e. 36 is "passed" to the sqrt function.
# the return value is 6 
sqrt(36)   
[1] 6

4.8 “passing values” to a function

#.......................................................................
# Specifying a value as an argument to a function is known as "passing" that value to the function. ####
#.......................................................................

sqrt(36)   # 36 is being "passed" to the sqrt function.
[1] 6
#.......................................................................
# The arguments to a function may be expressions, not just  single value. ####
#.......................................................................

2 * max ( pi ^ 2 , pi * 2)     # 1st argument: pi^2 , 2nd argument: pi*2
[1] 19.73921

4.9 more functions: ceiling, floor, sum

ceiling(3.2)   # ceiling rounds up to next higher number    ####
[1] 4
ceiling(-3.2)  # ... be careful with negatives    
[1] -3
floor (3.2)    # floor rounds down to nearest whole number   ####
[1] 3
floor(-3.2)    # ... be careful with negatives
[1] -4
sum(2,10,4)    # sum returns the sum of its arguments      ####
[1] 16
# we will speak about averages, or the "mean function" later ...

4.10 R’s “help” system    ?someFunction    ??anyWord

########################################################.
#
# R's "help" system    ####
#
########################################################.

#----------------------------------------------------------------------------.
# To get more information about a particular function, you 
# use the "help" function. You must put the name of the R function you 
# want help with in "quotes". The "help page" or "manual page" for 
# that function (or group of functions) will appear in the "help" 
# window.
#
#   help("sum") # show the R documentation page for the sum function.
#
#   help(sum)   # same thing - you don't need the quotes
#
#   ?sum        # same thing - ? is shorthand for the help function
#
#   ?help       # you can even get help on the help function
#
#   ??max       # The double question mark ?? searches for a particular word in any help page.
#----------------------------------------------------------------------------.

####

# Some help pages describe several different R functions in single page
#
#   ?ceiling   # this describes ceiling, floor and several other functions all in one help page
#
#   ?floor     # this shows the same thing

# NOTE: 
#
# In posit.cloud you can press F1 when the cursor is on the name of a function ####
# (this only works in the "script" window)

4.11 pi

# pi is a built-in variable that contains the first few digits of the value of pi

pi       # value of pi
[1] 3.141593
pi * 2   # pi times 2
[1] 6.283185
pi ^ 2   # pi quared
[1] 9.869604

4.12 trunc()

#-----------------------------------------------------------------------------.
# trunc function  ####
# 
# trunc stands for "truncate" which means to "shorten" or to "chop off"
# The trunc function "chops off" the values after the deicmal point.
#-----------------------------------------------------------------------------.

trunc(3.2)    # chops off the decimal points
[1] 3
trunc(-3.2)   # compare this with "floor and ceiling" ... how are they different? 
[1] -3

4.13 round() function

#-----------------------------------------------------------------------------.
# round function   ####
#
# first arugment - value to round
# second argument - which position to round
#-----------------------------------------------------------------------------.

# round a value to a particular number of decimal places
round(1.129, 2) # 1.13
[1] 1.13
round(1.129, 1) # 1.1
[1] 1.1
pi              # display the value of pi    ####
[1] 3.141593
round(pi, 2)    # round a value to a particular number of dcimal places
[1] 3.14
round(pi, 3)    # round a value to a particular number of dcimal places
[1] 3.142
# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# if 2nd argument is 0, the number is rounded to the closest whole number
# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

round(pi, 0)    # round pi to the closest whole number
[1] 3
#..........................................................................
# You can also supply a negative value for digits
#..........................................................................
round(1939, -1)  # negative values are allowed, e.g. round to closest multiple of 10
[1] 1940
round(1939, -2)  # round to closest multiple of 100
[1] 1900
round(1939.1598, 2)   # 1939.16
[1] 1939.16
round(1939.1598, -2)   # 1900
[1] 1900
#.................................................................
# Default value for the digits argument of the round function
#.................................................................

# Some arguments for some functions have a "default value". 
# The default value is used when the argument does not appear in the function call. 
# For example, 0 is the "default value" for the digits argument of the round function.
#
# This is described in the Usage section on the help page for the round function (?round)
# The usage section includes the following information:
#
#     USAGE: 
#        round(x, digits = 0)
#
# "digits = 0"   means that the defualt value of the
# digits argument (i.e. the 2nd argument) is 0 (zero).
#

round(pi)       # answer is 3 because 0 is the default number of digits
[1] 3
round(1.234)    # answer is 1 because 0 is the default number of digits
[1] 1
# ?round          # view the help page for the round function

4.14 Default values for arguments

#--------------------------------------------------------------------------------.
# NAMES AND DEFAULT VALUES OF ARGUMENTS ARE SHOWN ON THE HELP PAGES    ####
#
# The arguments for each function have "names"
#
# Some arguments have "default values". The default value for an argument is 
# used when the function call does NOT specify a value for that argument.
# (see examples below).
#--------------------------------------------------------------------------------.

# Every argument for every function in R has a "name".
# SOME arguments for SOME functions have a "default value".
# All of this information is shown in the "Usage" section on the help page 
# for the function.
#
# FOR EXAMPLE
#   Look at the help page for the round function (i.e. ?round).
#   The "Usage" section includes the following information:
#
#     USAGE: 
#        round(x, digits = 0)
#
#   This means 
#
#    - The name of the 1st argument is "x"
#
#    - The name of the 2nd argument is "digits".
#      The default value for the "digits" function is 0.
#      This is shown in the documentation as "digits = 0".
#
#    - Note that the first argument, x, does NOT have a default value.
#      

# View the help page by typing: 
#
#   ?round     # arguments are "x" and "digits", the default value for digits is 0

4.15 specifying arguments in function calls

# You may specify the names of the arguments when calling a function,
# but you don't have to (see examples below).
#
# Specifying the names of the arguments allows you to:
#
#   (a) type the arguments out of order (see below) and/or
#
#   (b) skip some arguments  (examples of this to be shown later ...)


# The following function call will round 12345 to the
# nearest hundred (i.e. the 2nd argument is -2) to result in 12300.
#
# The arguments must be specified in same order as specified on the help page
# (see ?round). i.e. first the number to be rounded (12345 in this case)
# and then the position to round it to (-2 in this case).

round( 12345, -2)   # round 12345 to the nearest hundred
[1] 12300
# You don't have to but you may specify the names of the arguments if you like.

round ( x=12345, digits=-2 )
[1] 12300
# If you specify the names of the arguments (see below), then you 
# may write the arguments out of order.
#
# Otherwise, the arguments must be typed in the same order as they appear
# in the "Usage" section on the help page.
# 
# In the following command the arguments are not in the order as specified
# on the help page. However, that is OK since we specified the names of the
# arguments.

round( digits = -2, x=12345)   # specify arguments out of order, same result as above
[1] 12300
# You may omit the names of the first few arguments in a function call.
# If you do so then the first few arguments, without names in the function call,
# are assumed to be the first few arguments as specified on the help page. 
#
# For example, in the following command the first argument, 12345,
# does not include a name. Since this is the first argument in the function
# call, it is assumed to be the "x" argument (which is the first argument
# specified in the help page (?round)).

round (12345, digits = -2) # you can specify names for some args but not others
[1] 12300
# If you want to, you MAY always specify the names of the arguments
# However, it is not necessary to type the names of the arguments as long as
# you type the arguments in the expected order (as defined in the help pages).
#
# Many R programmers choose to leave out names for the first argument or
# two and then specify names for the subsequent arguments,
# e.g. seq(2, 10, by=2) (this returns 2 4 6 8 10 - see ?seq). 
#
# The reason for this is that the first argument or two
# of most functions are obvious as to their meaning. After that, it becomes
# less clear as to what the additional arguments mean. By specifying the names
# of these additional arguments it becomes easier to read the code.

© 2025 Y. Rosenthal. All rights reserved.