R:使用环境中的对象名称制作数据框(例如tibble)

R: Make a data frame(such as tibble) using objects' names in the enviroment

require(tibble)

set.seed(1)

var_names <- c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')
for (variable in var_names) {
  assign(variable, sample(0:9, 10))
}

tibble(a, b, c, d, e, f, g, h, i, j)

> tibble(a, b, c, d, e, f, g, h, i, j)
# A tibble: 10 x 10
       a     b     c     d     e     f     g     h     i     j
   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
 1     2     2     9     4     8     4     9     3     4     2
 2     3     1     1     5     5     7     2     7     6     0
 3     4     5     5     3     6     3     3     2     3     5
 4     6     9     0     1     3     1     8     8     2     6
 5     1     4     8     9     7     0     7     6     9     4
 6     7     6     7     7     9     5     1     4     1     3
 7     8     7     6     8     0     6     4     9     8     1
 8     5     3     4     0     1     8     6     1     0     7
 9     9     0     2     6     2     2     0     5     7     9
10     0     8     3     2     4     9     5     0     5     8

我的问题是:有没有一种方法可以创建这个数据框而无需显式键入代码的最后一行,而只需引用环境中创建的对象的名称,就像这样:

tibble(对象(var_names))

因为我的实际代码有很多变量。

我们可以使用mget将全局环境中多个对象的值return转换为tibble

mget(var_names) %>% 
          as_tibble
# A tibble: 10 x 10
#       a     b     c     d     e     f     g     h     i     j
#   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
# 1     2     2     9     4     8     4     9     3     4     2
# 2     3     1     1     5     5     7     2     7     6     0
# 3     4     5     5     3     6     3     3     2     3     5
# 4     6     9     0     1     3     1     8     8     2     6
# 5     1     4     8     9     7     0     7     6     9     4
# 6     7     6     7     7     9     5     1     4     1     3
# 7     8     7     6     8     0     6     4     9     8     1
# 8     5     3     4     0     1     8     6     1     0     7
# 9     9     0     2     6     2     2     0     5     7     9
#10     0     8     3     2     4     9     5     0     5     8

另一种选择是使用 evalparse。类似于:

sapply(seq_along(var_names),function(x)eval(parse(text = var_names[x]))) %>%
as_tibble()

# A tibble: 10 x 10
      V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
#   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
# 1     2     2     9     4     8     4     9     3     4     2
#2     3     1     1     5     5     7     2     7     6     0
#3     4     5     5     3     6     3     3     2     3     5
#4     6     9     0     1     3     1     8     8     2     6
#5     1     4     8     9     7     0     7     6     9     4
#6     7     6     7     7     9     5     1     4     1     3
#7     8     7     6     8     0     6     4     9     8     1
#8     5     3     4     0     1     8     6     1     0     7
#9     9     0     2     6     2     2     0     5     7     9
#10     0     8     3     2     4     9     5     0     5     8