This lab should get you up and running with R! This is an R-Markdown file, which allows you to put text and code in the same document.
Change the author field on the Rmd document from Your Name Here to your own name.
Rename this file to “Lab1_YourHameHere.Rmd”, where YourNameHere is changed to your own name. Please do this from now on with the labs in the class.
Here’s an R code chunk that prints the text ‘Hello world!’ Press the green arrow to execute the code (this is like putting this in the console to be executed.)
print("Hello World!")
## [1] "Hello World!"
Use the code chunk below to print your name.
print("James Fraser")
## [1] "James Fraser"
my.vector <- c(25, -15, 7, 1006, 72)
In each of the following cases, use a single R command to obtain the required result: a. Add 6 to each element of my.vector. b. Square each element of my.vector. c. Sum the elements of my.vector. d. Sort the elements of my.vector in decreasing order. e. Display the 3rd element of my.vector. f. Display the 3rd and 5th element of my.vector. g. Display all the elements but the 4th of my.vector.
my.vector+6
## [1] 31 -9 13 1012 78
my.vector^2
## [1] 625 225 49 1012036 5184
sum(my.vector)
## [1] 1095
sort(my.vector)
## [1] -15 7 25 72 1006
my.vector[3]
## [1] 7
my.vector[3:5]
## [1] 7 1006 72
my.vector[-4]
## [1] 25 -15 7 72
adj<-c("Harder", "Faster", "Stronger", "Longer")
nouns<-c("Basic", "Java", "Matlab", "Python")
paste(adj, nouns)
## [1] "Harder Basic" "Faster Java" "Stronger Matlab" "Longer Python"
c()
operator, which forms a vector from its arguments. If we’re trying to build a vector containing a sequence of numbers, there are several ways to do this. These are the colon operator :
and the sequence function seq()
.:
Colon operator: execute these to see what happens!
1:20 # Numbers 1 to 20
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
227:232 # Numbers 227 to 232
## [1] 227 228 229 230 231 232
seq
function: seq(from, to, by)
: again, execute!
seq(1,10,1) # Numbers 1 to 10
## [1] 1 2 3 4 5 6 7 8 9 10
seq(1,10,2) # Odd numbers from 1 to 10
## [1] 1 3 5 7 9
seq(2,10,2) # Even numbers from 2 to 10
## [1] 2 4 6 8 10
Now you try it. Use :
to:
13:22
## [1] 13 14 15 16 17 18 19 20 21 22
100:91
## [1] 100 99 98 97 96 95 94 93 92 91
seq()
to output the sequence of numbers from 3 to 30 in increments of 3seq(3,30, 3)
## [1] 3 6 9 12 15 18 21 24 27 30
x
, and the sequence from b. as a variable y
. Create a new variable ‘z’ which is obtained by multiplying ‘x’ and ‘y’ component-wise.x<-c(13:22)
y<-c(100:91)
z<-x*y
x*y
## [1] 1300 1386 1470 1552 1632 1710 1786 1860 1932 2002
z
## [1] 1300 1386 1470 1552 1632 1710 1786 1860 1932 2002