Home > Mobile >  Cbind get environment objects in R
Cbind get environment objects in R

Time:11-06

I would like cbind the vectors of same dimension using a vector of their names.

For example I would like get from

a <- c(2, 5, NA, NA, 6, NA)
b <- c(NA, 1, 3, 4, NA, 8)

A matrix using cbind(a,b)

      a  b
[1,]  2 NA
[2,]  5  1
[3,] NA  3
[4,] NA  4
[5,]  6 NA
[6,] NA  8

but calling variables from a vector of environment objects names, e.g. vectornames <- c("a","b")

My last try failed on cbind(for(i in vectornames) get(i))

CodePudding user response:

You want to sapply/lapply the get function here. For example:

a <- c(2, 5, NA, NA, 6, NA)
b <- c(NA, 1, 3, 4, NA, 8)
nmes <- c("a", "b")

# Apply get() to each name in the nmes vector
# Then convert the resulting matrix to a data frame
as.data.frame(sapply(nms, get))
   a  b
1  2 NA
2  5  1
3 NA  3
4 NA  4
5  6 NA
6 NA  8

Technically you can do this using cbind, but it's more awkward:

# Convert the vector of names to a list of vectors
# Then bind those vectors together as columns
do.call(cbind, lapply(nms, get))

CodePudding user response:

We can use mget to 'get' a list, then "loop-unlist" with sapply and function(x) x or [ to create a matrix

sapply(mget(vectornames), \(x) x)

#OR

sapply(mget(vectornames), `[`)

      a  b
[1,]  2 NA
[2,]  5  1
[3,] NA  3
[4,] NA  4
[5,]  6 NA
[6,] NA  8
  • Related