r_vectors Flashcards
What are 2 ways to do the following?
Create a vector named “codes” with the following characteristics:
- Three regions with corresponding values
- italy = 380
- canada = 124
- egypt = 818
Way 1: codes <- c(“italy”=380, “canada”=124, “egypt”=818)
Way 2:
- > codes <- ‘a’
- > codes <- c(380,124,818)
- > country <- c(“italy”,”canada”,”egypt”)
- > names(codes) <- country
- > codes
Create a sequence from 1 to 10
Create a sequency from 1 to 10, in intervals of 2
seq(1,10)
seq(1,10,2)
How do you get the second element of the vector “codes”
codes[2]
How do you get the first and third elements of the vector “codes”
codes[c(1,3)]
How do you access the first thru the third elements of the vector “codes”
codes[1:3]
How do you access the element named “canada” within the vector “codes”
codes[“canada”]
- How do you access the elements named “egypt” and “italy” within the vector “temp”?
- Way 1: names
- Way 2: index values 3 and 5
- Way 1: temp[“egypt”,”italy”]
- Way 2: temp[c(3,5)]
What is “coercion” in R
- When R attempts to coerce a value into a data type it “thinks” it should be, when incomplete or contradicting information is provided.
As an example of coercion:
- What happens if you type the following:
- x <- c(1, “canada”, 3)
- R will create a vector of three character strings (converting 1 and 3 to strings)
- Output of x: “1” “canada” “3”
How would you convert the vector 1:5 into characters
- x < 1:5
- y < as.character(x)
What would happen if you type the following code:
- x <- c(“1”, “b”, “3”)
- as.numeric(x)
- R tries coercion
- Output:
- 1 NA 3
- Warning message: NAs introduced by coercion
Associate the “city” vector to the “temp” vector
names(temp) <- city
Get the first three cities in the temp vector
temp[1:3]