Adam Kurkiewicz - 2 months ago 14

R Question

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")`

`vec3`

`vec1`

`vec2`

In other languages

`vec3`

`vec1`

`vec2`

`vec1`

`vec2`

Let's say that I want to combine

`vec1`

`vec2`

`c("v1"=1, "v2"=2, "v3"=3)`

`vec3`

Let's say that I want to reverse

`vec3`

`c("v1"="h1", "v2"="h2", "v3"="h3")`

`vec3`

How can I get from

`vec3`

`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"
```