# vectors_arithmetic_recycling.R
# Introduction to R: Vectors, Arithmetic, and Recycling
# Ken Hanscombe 2012
#===============#
# EXERCISE #
#===============#
# 1. Pick out every third letter in the alphabet.
# Can you do this using (i) numeric vector argument and
# (ii) a logical argument in [ ]
letters[seq(1,26,3)]
letters[c(T,F,F)]
# 2. Calculate the sum of odd numbers up to 1000.
odd_numbers<-(1:1000)[c(T,F)]
sum(odd_numbers)
# 3. What's the largest multiple of 13 under 1000?
13 * (1000 %/% 13)
1000 - (1000 %% 13)
# 4. Can you figure out what each of these will return? Test yourself.
# 100 / 3
# 100 %% 3
# 100 %/% 3
# '+'(2,3)
# 2 + 3
# a <- 1:100
# a
# a + 0.5
# a + a
# 5. Generate a vector with 50 random integers from a uniform distribution between 0 and 100 (HINT: Use round() ).
# How long is the vector formed from all the even numbers?
unif_numbers<-round(runif(50,0,100))
even_nums <- unif_numbers[unif_numbers %% 2 == 0]
length(even_nums)
# 6. Calculate pi using the Leibniz formula
# generate the vector of odd numbers; invert them
# use the recycle rule to make every second number negative
# multiply the sum by 4
n<-1000
sum((1/seq(1,n,2))*c(+1,-1))*4