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?
P1<-c(23,45,67,46,57,23,83,59,12,64)
max(P1)
## [1] 83
min(P1)
## [1] 12
# to get both:
range(P1)
## [1] 12 83
mean(P1)
## [1] 47.9
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?
P1[9]
## [1] 12
# use same approach to change it
P1[9]<-42
mean(P1)
## [1] 50.9
# mean has increased from 47.9 to 50.9 - 3 units
How many values are greater than 40? What is the mean of values over 40?
P1>40
## [1] FALSE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE
# A logical vector, TRUE=1 so
sum(P1>40)
## [1] 8
# gives us a count of values > 40
# we could also use:
length(which(P1>40))
## [1] 8
# for mean of values greater than 40 we put the logical test inside the []:
P1[P1>40]
## [1] 45 67 46 57 83 59 42 64
#logical extraction
mean(P1[P1>40])
## [1] 57.875
Using the data from problem 1 find:
a) the sum of P1
sum(P1) (509)
b) the mean (using the sum and length(P1))
sum(P1)/length(P1) (50.9)
c) the log(base10) - use log(base=10)
log(P1,base=10) (1.3617278, 1.6532125, 1.8260748, 1.6627578, 1.7558749, 1.3617278, 1.9190781, 1.770852, 1.6232493, 1.80618) - could also use log10()
d) the difference between each element of P1 and the mean of P1
P1-mean(P1) (-27.9, -5.9, 16.1, -4.9, 6.1, -27.9, 32.1, 8.1, -8.9, 13.1)
If we have two vectors, a=11:20 and b=c(2,4,6,8) describe (without running the code) the outcome of the following (check yourself by running the code):
a) a*2
22:40
b) a[b]
2nd,4th, 6th and 8th elements of a, i.e. 12,14,16,18. Since b is 2,4,6,8, you can think of this as a[c(2,4,6,8)].
c) b[a]
NA because there are only 4 elements in B therefore the 11th-20th elements are NA
d) c(a,b)
a combined with b into a single vector: 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 2, 4, 6, 8
e) a+b
first 4 elements of a added to the 4 elements of b, next 4 elements of a added to b, last 2 elements of a added to first 2 elements of b, with a warning message.
13,16,19,22,17,20,23,26,21,24