# Loop across vector of numbers
for(k in 1:5){
# Square that number
square_k <- k * k
# Print that result
print(square_k)
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
After today’s session you will be able to:
# Start of loop
for ( index in vector ) {
# Actual operation of loop
function(index)
} # End of loop
{
/}
) to define start/end
?sqrt
)print
function)
print
is the one we’ll focus on!
print
only accepts one vector at a time
paste
makes multiple vectors into one vectorprint
+ paste
print
and paste
to assemble informative messages!
# Use `paste` to combine multiple vectors
text <- paste("Hello", "my", "name", "is", "Nick")
# Then give that to `print` to return!
print(text)
[1] "Hello my name is Nick"
print
and paste
to make messages
# Loop across vector of numbers
for(k in 1:5){
# Square that number
square_k <- k * k
# Print a message about that result
print(paste("The square of", k, "is", square_k))
}
[1] "The square of 1 is 1"
[1] "The square of 2 is 4"
[1] "The square of 3 is 9"
[1] "The square of 4 is 16"
[1] "The square of 5 is 25"
print
step tell you the starting number and its square root
==
, &
, >
, etc.
if
& else
if
wants:
(...)
{...}
else
wants:
{...}
bitsif
is used first
if
if
s
# If the number is less than 0
if(x < 0){
print("Number is negative")
# If it's more than 0
} else if(x > 0){
print("Number is positive")
# Otherwise ...
} else {
print("Number is zero")
}
else if(...){...}
?
# Test vector
my_vec <- c(-10, -9, -8, 0, 4, 5, 6)
# Loop across it
for(value in my_vec){
# Make negative numbers positive
if(value < 0){
print(value * -1)
# Take the square root of positive numbers
} else if(value > 0){
print(sqrt(value)) }
} # Close loop curly brace
[1] 10
[1] 9
[1] 8
[1] 2
[1] 2.236068
[1] 2.44949
g
as the index
g
is less than 14, print
“Less than 14”print
the value as-is