#############################
## Chapter 1. Basics
### The console, the editor, and basic syntax in R
2 + 2
## [1] 4
4*5
## [1] 20
6^2
## [1] 36
3+5*2
## [1] 13
(3+5)*2
## [1] 16
# 2+2
a = 5# =
a
## [1] 5
a*2
## [1] 10
a
## [1] 5
a=a*2
sms=c(0,1,2,0,0,0,1)
sms + 5
## [1] 5 6 7 5 5 5 6
sms * 5
## [1] 0 5 10 0 0 0 5
sms/2
## [1] 0.0 0.5 1.0 0.0 0.0 0.0 0.5
sort(sms)
## [1] 0 0 0 0 1 1 2
sms[3]
## [1] 2
sms[2:4]
## [1] 1 2 0
sms[-3]
## [1] 0 1 0 0 0 1
sms[-(2:3)]
## [1] 0 0 0 0 1
sms[-c(2,3,7)]
## [1] 0 0 0 0
sms>0
## [1] FALSE TRUE TRUE FALSE FALSE FALSE TRUE
sms[sms>0]
## [1] 1 2 1
sum(sms>0)
## [1] 3
which(sms>0)
## [1] 2 3 7
sms[which(sms>0)]
## [1] 1 2 1
mean(sms[which(sms>0)])
## [1] 1.333333
sms
## [1] 0 1 2 0 0 0 1
sms[1]=1
sms
## [1] 1 1 2 0 0 0 1
1:50
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
## [24] 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
## [47] 47 48 49 50
x=c("a","b","c","d","e","f","g","h","i")
y=21:30
z=c(2,4,6)
x[y]
## [1] NA NA NA NA NA NA NA NA NA NA
x[z]
## [1] "b" "d" "f"
y[z]
## [1] 22 24 26
z[y]
## [1] NA NA NA NA NA NA NA NA NA NA
x[rev(z)]
## [1] "f" "d" "b"
y[x]
## [1] NA NA NA NA NA NA NA NA NA
y*z
## Warning in y * z: longer object length is not a multiple of shorter object
## length
## [1] 42 88 138 48 100 156 54 112 174 60
# Function | Description
# sd() | standard deviation
# median() | median
# max() | maximum
# min() | minimum
# range() |maximum and minimum
# length() | number of elements of a vector
# cummin() | cumulative min (or max cummax() )
# diff() | differences between successive elements of a vector
for (i in 1:27) {cat(letters[i])}
## abcdefghijklmnopqrstuvwxyzNA
for (i in sample(x = 1:26,size = 14)) cat(LETTERS[i])
## HOYDMKQITAJZWG
x<-c("Most","loops","in","R","can","be","avoided")
for (i in x){cat(paste(i,"!"))}
## Most !loops !in !R !can !be !avoided !
###### VI. Exercises. ######
## 1)## Enter the following data in R and call it `P1`:
# `23,45,67,46,57,23,83,59,12,64`
# What is the maximum value? What is the minimum value? What is the mean value?
## 2)## Oh no! The next to last (9th) value was mistyped - it should be 42. Change it, and see how the mean has changed. How many values are greater than 40? What is the mean of values over 40?
# Hint: how do you see the 9th element of the vector `P1`?
## 3)## Using the data from problem ##2## find:
# a) the sum of `P1`
# b) the mean (using the sum and `length(P1)`)
# c) the log(base10) of `P1` - use `log(base=10)`
# d) the difference between each element of `P1` and the mean of `P1`
## 4)## If we have two vectors, `a=11:20` and `b=c(2,4,6,8)` predict (_without running the code_) the outcome of the following (Include your predictions as comments. After you make your predictions, you can check yourself by running the code):
# a) `a*2`
# b) `a[b]`
# c) `b[a]`
# d) `c(a,b)`
# e) `a+b`