Solutions
For part (1) instead of feeding single numbers as inputs to the function, we try an integer
vector instead. Since the function has two inputs, we can try an integer
vector as the first input (and singleton as the second), vice versa, or integer
vectors for both inputs.
do.something(10, 3) # singleton inputs
[1] 5
do.something(1:10, 3) # first input is a vector, output is also a vector
[1] 2.00 2.33 2.67 3.00 3.33 3.67 4.00 4.33 4.67 5.00
do.something(1:10, seq(1, 20, by = 2)) # both inputs are vectors, as is the output
[1] 6.000 2.333 1.600 1.286 1.111 1.000 0.923 0.867 0.824 0.789
For part (2), here's how we can show that ifelse
is vectorized:
ifelse(2 > 1, 55, 0) # singleton condition and output
[1] 55
ifelse(0:5 > 1, 55, 0) # condition is vector, so is the output
[1] 0 0 55 55 55 55
ifelse(0:5 > 1, letters[1:6], LETTERS[1:6]) # all inputs are vectors, so is the output
[1] "A" "B" "c" "d" "e" "f"
However, if
and else
are not vectorized functions, as can be seen by the following example:
if(2 > 1) 55 else 0 # singleton condition works fine
[1] 55
if(0:5 > 1) 55 else 0 # vector of conditions does not work (only the first element) is considered
Warning in if (0:5 > 1) 55 else 0 :
the condition has length > 1 and only the first element will be used
[1] 0
This means that we generally use ifelse
when we need to transform the data (e.g. create a new column) based on conditional statements, whereas we use if
and else
when we need to check a single condition, such as this:
if(file.exists("NYC_Sample.csv")) sprintf("%s/%s exists.", getwd(), "NYC_Sample.csv")
[1] "C:/Data/NYC_taxi/NYC_Sample.csv exists."