Extract vectors from a vector set of vector names and merge into a single vector

Asked

Viewed 49 times

5

I have a vector that contains names of other vectors. For example:

teste
[1] "vetor_arte"   "vetor_rio"    "vetor_parque"

vetor_arte
[1]  1  3  4 11 12 13 14 16 29 30 41

vetor_rio
[1]  6  7  8  9 10

vetor_parque
[1]  5 15 17 27

I want a general vector:

vetor_geral
[1] 1  3  4 11 12 13 14 16 29 30 41 6  7  8  9 10 5 15 17 27

Manually I can, but I want to do it dynamically because my initial vector will sometimes contain names of 3, 4, 2, 5 vectors. It is not a fixed vector.

I’m having trouble developing that logic.

2 answers

4

What either can be done with a single instruction R base.
The main function to be used is mget. Then just turn into vector (unlist) nameless (unname).

vetor_geral <- unname(unlist(mget(teste)))
vetor_geral
# [1]  1  3  4 11 12 13 14 16 29 30 41  6  7  8  9 10  5 15 17 27

Dice.

teste <- scan(what = character(), text = '
"vetor_arte"   "vetor_rio"    "vetor_parque"')

vetor_arte <- scan(text = '
1  3  4 11 12 13 14 16 29 30 41')

vetor_rio <- scan(text = '
6  7  8  9 10')

vetor_parque <- scan(text = '
5 15 17 27')

4


First I will create the data to be used in this problem:

teste <- c("vetor_arte", "vetor_rio", "vetor_parque")

vetor_arte <- c(1,  3,  4, 11, 12, 13, 14, 16, 29, 30, 41)
vetor_rio <- c(6,  7,  8,  9, 10)
vetor_parque <- c(5, 15, 17, 27)

The function ls lists the objects in the memory of R. Here I’ll ask her to list all the objects they have vetor in his some:

ls(pattern="vetor")
[1] "vetor_arte"   "vetor_parque" "vetor_rio"   

Then combine this result with the function lapply, in order to create a list of the three desired vectors. Note that I have lost information about the name of the vectors, but this is not important in this case.

lista <- lapply(ls(pattern="vetor"), get)
lista
[[1]]
[1]  1  3  4 11 12 13 14 16 29 30 41

[[2]]
[1]  5 15 17 27

[[3]]
[1]  6  7  8  9 10

Finally, I create the object vetor_geral when undoing the list created in the previous step:

vetor_geral <- unlist(lista)
vetor_geral
[1]  1  3  4 11 12 13 14 16 29 30 41  5 15 17 27  6  7  8  9 10

The disadvantage of this method is to put the vectors in alphabetical order. If the order vetor_arte, vetor_rio and vetor_parque be important, my solution does not work satisfactorily.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.