创建一个包含数百列的新 tibble

Creating a new tibble with hundreds of columns

我想使用 tidyverse 中的函数创建一个 tibble 的数百列,我不想逐列输入它们。

是否可以使用 tibble() 函数 创建具有列名 tibble? (请注意,我喜欢 tibble() 按顺序创建列的方式,因此在 tibble() 中包装基本 R 解决方案可能不会令人满意)。

对于更具体的工作示例,让解决方案调用 tibble() 创建一个 5 列 tbl,其中包含 10 个随机采样的 1 到 10 之间的整数 (sample(10))在第 1 列和由前一列 + sample(10) 计算的每个后续列中。例如,下面的代码 而不是 使用 "col2=..." 创建每个列:

set.seed(1)
tibble(col1 = sample(10),
       col2 = col1 + sample(10),
       col3 = col2 + sample(10),
       col4 = col3 + sample(10),
       col5 = col4 + sample(10))

# A tibble: 10 x 5
    col1  col2  col3  col4  col5
   <int> <int> <int> <int> <int>
 1     9    12    17    18    22
 2     4     5    14    18    27
 3     7    12    13    16    23
 4     1     9    15    21    27
 5     2     4    14    16    17
 6     5    11    18    25    35
 7     3    13    15    20    28
 8    10    19    23    31    34
 9     6    10    13    22    24
10     8    15    23    33    38

编辑

好吧,显然这可能无法单独使用 tibble()(待定)。是否可以使用 tibble() 函数创建一个 tbl,其中 100 列分别命名为 col1col2、... col100?我不在乎里面是什么!

我怀疑您是否会喜欢这个解决方案,但这是使用 for 循环的一种方法

library(dplyr)
library(rlang)

set.seed(1)
df <- tibble::tibble(col1 = sample(10))
n <- 10

for (i in seq_len(n)[-1])  {
   df <- df %>% mutate(!!paste0("col",i) := !!sym(paste0("col", i-1)) + sample(10))
}


df
# A tibble: 10 x 10
#    col1  col2  col3  col4  col5  col6  col7  col8  col9 col10
#   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
# 1     9    12    17    18    22    32    38    42    48    54
# 2     4     5    14    18    27    34    35    43    44    46
# 3     7    12    13    16    23    26    29    30    35    44
# 4     1     9    15    21    27    29    37    46    54    57
# 5     2     4    14    16    17    23    33    39    49    59
# 6     5    11    18    25    35    44    48    58    67    75
# 7     3    13    15    20    28    29    31    34    41    45
# 8    10    19    23    31    34    39    46    53    56    63
# 9     6    10    13    22    24    32    41    46    50    51
#10     8    15    23    33    38    42    47    49    51    56