Search code examples
rvectorrbindr-environment

How to call several vectors into the r environment to use them in another function


I have a serie of vectors with different lengths within the R environment, for example:

> s_aleat_0
[1] "12M08393" "12M08427" "12M08412" "12M08441" "12M08436" "12M08444" "12M08443" "12M08387"
> s_aleat_1
[1] "12M08405" "12M08389" "12M08439" "12M08406" "12M08397" "12M08402"
> s_aleat_2
[1] "12M08422" "12M08441" "12M08410" "12M08391" "12M08396" "12M08420" "12M08409"

And I want call them by pattern into another funtion (rbind his character strings to join the initial vectors in a bigger one) like that:

samples<-ls(pattern = "s_aleat_")
unique(c(rbind(samples)))
     [1] "12M08393" "12M08405" "12M08422" "12M08427" "12M08389" "12M08441" "12M08412" "12M08439" "12M08410"
    [10] "12M08406" "12M08391" "12M08436" "12M08397" "12M08396" "12M08444" "12M08402" "12M08420" "12M08443"
    [19] "12M08409" "12M08387"

But when I put 'samples' inside rbind it doesn't recognize the vectors, if not the text obtained with ls function as I show below:

c(rbind(samples))
[1] "s_aleat_0" "s_aleat_1" "s_aleat_2" "s_aleat_4" "s_aleat_5"

How I could fixed it?


Solution

  • You can collect all the vectors in a list using mget and append NA's for vector with shorter length to create a matrix where each vector is a column.

    s_aleat_0 <- c("12M08393","12M08427","12M08412","12M08441","12M08436","12M08444","12M08443","12M08387")
    s_aleat_1 <- c("12M08405", "12M08389", "12M08439", "12M08406", "12M08397" ,"12M08402")
    s_aleat_2 <- c( "12M08422", "12M08441", "12M08410" ,"12M08391", "12M08396", "12M08420", "12M08409")
    
    tmp <- mget(ls(pattern = "s_aleat_"))
    result <- sapply(tmp, `[`, 1:max(lengths(tmp)))
    
    #     s_aleat_0  s_aleat_1  s_aleat_2 
    #[1,] "12M08393" "12M08405" "12M08422"
    #[2,] "12M08427" "12M08389" "12M08441"
    #[3,] "12M08412" "12M08439" "12M08410"
    #[4,] "12M08441" "12M08406" "12M08391"
    #[5,] "12M08436" "12M08397" "12M08396"
    #[6,] "12M08444" "12M08402" "12M08420"
    #[7,] "12M08443" NA         "12M08409"
    #[8,] "12M08387" NA         NA