- Storethevalues − 20, − 15, − 5, 8, 12, 9, 2, 23, 19 in the R
variable x and use the R command sum to verify that the sum of the
values is 33.
x <- c(-20,-15,-5,8,12,9,2,23,19)
sum(x)
## [1] 33
- For the data in Exercise 1, verify that the average is 3.67 using
the R command mean
mean(x)
## [1] 3.666667
- What R commands can be used to compute an average without using the
R command mean ?
sum(x)/length(x)
## [1] 3.666667
- In Exercise 1, use R to sum the positive values ignoring the
negative values.
sum(x[x>0])
## [1] 73
- In Exercise1, use the which command to get the average of the values
ignoring the largest value.
mean(x[x<max(x)])
## [1] 1.25
- If the data in Exercise1 are stored in the variable x , speculate
about the values corresponding to x[abs(x)>=8 & x<8] . Verify
your speculation using this R command.
Speculation: This command will return values of x that have an
absolute value greater than or equal to 8 and a value less than 8.
Namely, -20 and -15
x[abs(x)>=8 & x<8]
## [1] -20 -15
- You record your commute time to work for 10 days, in minutes, and
get 23, 18, 29, 22, 24, 27, 28, 19, 28, 23. Use R to determine the
average, the shortest time, and the longest time.
t <- c(23,18,29,22,24,27,28,19,28,23)
mean(t)
## [1] 24.1
min(t)
## [1] 18
max(t)
## [1] 29
- Verify that the commands y=c(2,4,8) z=c(1,5,2) 2*y return the values
4, 8, 16. Also, verify that the R command y+z returns 3, 9, 10 and that
the command y-2 returns 0,2,6.
y=c(2,4,8)
z=c(1,5,2)
2*y
## [1] 4 8 16
y+z
## [1] 3 9 10
y-2
## [1] 0 2 6
- Let x = c(1, 8, 2, 6, 3, 8, 5, 5, 5, 5) . Use R to compute the
average using the sum and length commands. Next, use a single command to
subtract the value 4 from each value stored in x. Finally, find the
difference between the largest and smallest values stored in x. (This
difference is called the range.) You can use the max and min functions
or the range function.
x = c(1, 8, 2, 6, 3, 8, 5, 5, 5, 5)
x-4
## [1] -3 4 -2 2 -1 4 1 1 1 1
max(x)-min(x)
## [1] 7
- For the data in Exercise 9, use R to subtract the average from each
value, and then sum the results.
x-mean(x)
## [1] -3.8 3.2 -2.8 1.2 -1.8 3.2 0.2 0.2 0.2 0.2
sum(x-mean(x))
## [1] 1.776357e-15