2/1/2021

New Thinking

There are certain patterns you have learned in other computer languages which you will want to change when you work in R.

Computing a Sum

One of the standard paradigms in most languages to accomplish a task is as follows.

  1. Initialize an object
  2. Iterate over a collection to modify the object.

We can compute the sum of the numbers in a numeric vector in R just like we did it in python. Here’s an example of how this would be done by a newbie in R still thinking in python, etc..

Get some numbers. I’ll just get random numbers from a normal distribution.

x = rnorm(10)
x
##  [1] -1.8147688 -1.5718304 -1.7492595  0.2064380 -0.9178106 -0.5669545
##  [7] -0.2974227 -0.1362099  0.7484115 -0.2508738

Loopy Solution

Write a for loop to add these numbers.

Answer

total = 0 # Initialize

# Now loop and modify
for(i in 1:10){
  
  total = total + x[i]
}

# Display the result
total
## [1] -6.350281

The R Way.

Do it the R way by vectorizing your thinking.

Answer

total = sum(x)
total
## [1] -6.350281

The Point

I do a lot of programming in R. I use for loops so rarely that I have to stop and think about the syntax when I do use one.

R was designed by statisticians to make what they do very easy. Vectors are the basic building block in R. Normal values are just vectors of length 1.