Brigadeiro
Brigadeiro

Reputation: 2945

Creating a new tibble with hundreds of columns

I want to create a tibble using functions from the tidyverse with hundreds of columns, and I don't want to type them out column-by-column.

Is it possible to create a tibble with column names using the tibble() function? (Note, I like how tibble() creates columns sequentially, so wrapping base R solutions in tibble() likely won't be satisfying).

For a more concrete working example, let the solution be a call to tibble() creating a 5-column tbl with 10 randomly sampled integers between 1 and 10 (sample(10)) in column 1 and each subsequent column calculated by the previous column + sample(10). For example, the following code but not using "col2=..." to create each column:

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

Edit

Okay, apparently this might be impossible with tibble() alone (TBD). Is it possible to create a tbl using the tibble() function with 100 columns each named col1, col2, ... col100? I don't care what's inside!

Upvotes: 2

Views: 619

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

I doubt if you are going to like this solution but here is one way using a for loop

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

Upvotes: 2

Related Questions