In: Computer Science
R-Studio (R Programming Language)
1. How would you create a vector `V` containing the values 0,
0.25, 0.5, 0.75, and 1?
```{r}
#insert your code
```
2. Name the elements of `V`: first, second, middle, fourth, last.
Describe two ways of naming elements in `V`
```{r}
#insert your code
```
3. Suppose you keep track of your mileage each time you fill up.
At your last 6 fill-ups the mileage was
65311 65624 65908 66219 66499 66821 67145 67447. Enter these
numbers into R as vector `miles`. Use the function `diff` on the
data `miles`. What does it give? Use `sum` on the computed
differences to find the total travelled distance.
```{r}
#insert your code
```
In case of any query, do comment. Please rate answer. Thanks .
Code is as below:
#R version 3.3.2
#create a vector `V` containing the values 0, 0.25, 0.5, 0.75, and 1
V <- c(0, 0.25, 0.5, 0.75, 1)
#first way to name elements
names(V) <- c("first","second","middle", "fourth","last")
#another way to name element is using setnames method as below
V <- setNames(1:5, c("first","second","middle", "fourth","last"))
#Below line is used to verify the output, you can remove it
V
#create a vector miles using difference mileage readings
miles <- c(65311, 65624, 65908, 66219, 66499, 66821, 67145, 67447)
#diff gives the difference between the element in vector mileage2-mileage1, mileage3-mileage2,
#mileage4-mileage3, mileage5-mileage4, mileage6-mileage5, mileage7-mileage6
print("difference in miles: ")
diff(miles)
#to calculate the sum of total traveled distance
print("Total traveled distance :")
sum(diff(miles))
================screen shot of the code================
Output:
Output after using second way of naming the element using setNames
Output after doing diff on Miles and then sum for getting total traveled distance: