Adam Kurkiewicz Adam Kurkiewicz - 20 days ago 6
R Question

Transforming R's vectors

I'm learning basics of R and I'm very confused by R's "vectors" and how to transform them.

Basically, I know that these are examples of vectors:

vec1 <- c("v1", "v2", "v3")


vec2 <- c(1, 2, 3)


vec3 <- c("h1"="v1", "h2"="v2", "h3"="v3")


Q1. Why is
vec3
so different from
vec1
and
vec2
?



In other languages
vec3
would be an example of "dictionary" or "hashmap", whereas
vec1
and
vec2
would be examples of "lists" or "arrays".

Q2. How can I combine
vec1
and
vec2
?



Let's say that I want to combine
vec1
and
vec2
into
c("v1"=1, "v2"=2, "v3"=3)
.

Q3. How can I reverse keys with values in
vec3
?



Let's say that I want to reverse
vec3
into
c("v1"="h1", "v2"="h2", "v3"="h3")
. (Let's say that all values are always unique).

Q4. How can I extract a vector of values from
vec3
?



How can I get from
vec3
into
c("v1", "v2", "v3")

Answer

Check this out:

A1

  • vec1 : is a character vector

  • vec2 : is a numeric vector

  • vec3: is a named vector

you can get values by name:

> vec3["h1"]
  h1 
"v1" 

A2

names(vec2) <- vec1

> vec2
v1 v2 v3 
 1  2  3 

A3

vec4 <- vec3
vec4 <- names(vec4)
names(vec4) <- vec3
vec3 <- vec4

> vec3
  v1   v2   v3 
"h1" "h2" "h3"

A4

> names(vec3) <- NULL
> vec3
[1] "v1" "v2" "v3"