Let’s look at some basic commands in R.

Set up the following vector by cutting and pasting from this document:

`a <- c(3,-7,-3,-9,3,-1,2,-12, -14)`

`b <- c(3,7,-5, 1, 5,-6,-9,16, -8)`

`d <- c(1,2,3,4,5,6,7,8,9)`

Now figure out what each of the following commands do. You should not need me to explain each command, but I will explain a few.

`a*a `

` a + b `

` a - d `

`a / d `

`a*d`

`a^2`

`a[7] `

`a[c(1,4,7)]`

`a[-c(5,6)] `

`length(a)`

`a[length(a)] `

`a[-length(a)] `

`length(a[c(1, 2, 3)])`

`a[8] `

`a[c(7, 5, 3)] `

`a>2`

`a[a >2]`

`a[-c(3, 5, 6)] `

`a^2 `

`a**2`

` a + 99`

`min(b)`

`min(a,b,d)`

`max(a,b,d)`

`max(b)`

`mean(a)`

`median(d)`

`range(a) `

`unique(a,b, d)`

`length(unique(a,b, d))`

The syntax `a > 2`

gives a list of values that are either TRUE or FALSE depending on whether each value meets the criterion of being greater than 2.

This list of values is called a vector, but don’t let the mathematical language intimidate you. It’s just a named list.

Then the syntax `a[a >2]`

subsets the vector a to a smaller set of values that are indeed greater than 2.

Again, the data values in the list are called elements.

You can see that these elements are identified and indexed using square brackets. Elements are retained if the indices are positive, and excluded if the indices are negative. Note that `a[length(a)] `

picks out the last element in the list, while` a[-length(a)] `

removes the last element. Of course, `length(a)`

gives the number of elements in the vector a.

Suppose that you wished to remove the last element of a vector permanently, you could do this:

`a <- a[-length(a)]`

`a`

`[1] 3 -7 -3 -9 3 -1 2 -12`

The last element (-14) has been removed.

That wasn’t so hard! In my next post, I will look at further statistical techniques in R.

About the Author:*David Lillis has taught R to many researchers and statisticians. His company, Sigma Statistics and Research Limited, provides both on-line instruction and face-to-face workshops on R, and coding services in R.
*

## Leave a Reply