r_vectors Flashcards

1
Q

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
A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Create a sequence from 1 to 10

Create a sequency from 1 to 10, in intervals of 2

A

seq(1,10)

seq(1,10,2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you get the second element of the vector “codes”

A

codes[2]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you get the first and third elements of the vector “codes”

A

codes[c(1,3)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you access the first thru the third elements of the vector “codes”

A

codes[1:3]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you access the element named “canada” within the vector “codes”

A

codes[“canada”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
  • How do you access the elements named “egypt” and “italy” within the vector “temp”?
    • Way 1: names
    • Way 2: index values 3 and 5
A
  • Way 1: temp[“egypt”,”italy”]
  • Way 2: temp[c(3,5)]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is “coercion” in R

A
  • When R attempts to coerce a value into a data type it “thinks” it should be, when incomplete or contradicting information is provided.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

As an example of coercion:

  • What happens if you type the following:
  • x <- c(1, “canada”, 3)
A
  • R will create a vector of three character strings (converting 1 and 3 to strings)
  • Output of x: “1” “canada” “3”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How would you convert the vector 1:5 into characters

A
  • x < 1:5
  • y < as.character(x)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What would happen if you type the following code:

  • x <- c(“1”, “b”, “3”)
  • as.numeric(x)
A
  • R tries coercion
  • Output:
    • 1 NA 3
    • Warning message: NAs introduced by coercion
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Associate the “city” vector to the “temp” vector

A

names(temp) <- city

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Get the first three cities in the temp vector

A

temp[1:3]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly