【问题标题】:Creating a new tibble with hundreds of columns创建一个包含数百列的新 tibble
【发布时间】:2019-08-20 00:26:02
【问题描述】:

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

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

对于更具体的工作示例,让解决方案是调用 tibble() 创建一个 5 列 tbl,在第 1 列中包含 10 个 1 到 10 (sample(10)) 之间的随机抽样整数,然后计算每个后续列按上一栏 + 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?我不在乎里面是什么!

【问题讨论】:

  • 听起来像是 R 中的 Reduce 操作,虽然它不在 tibble 世界中,但它确实给出了相同的值:- set.seed(1); Reduce(`+`, replicate(5,list(sample(10))), accumulate=TRUE)
  • 或者如果你更熟悉tidyverse中的purrr,那么accumulate(rerun(5, sample(10)), `+`)

标签: r dplyr tibble


【解决方案1】:

我怀疑你是否会喜欢这个解决方案,但这是使用 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

【讨论】:

  • 谢谢!坚持寻求一个更简单的解决方案,但如果没有其他问题弹出,就会给你! (另外,请参阅我最近的编辑)
  • @Brigadeiro 我不确定在这种情况下是否可以区别对待tibble。就您的新编辑而言,也许您可​​以这样做n = 10; as_tibble(matrix(sample(100), ncol = 10, dimnames = list(NULL, paste0("col", seq_len(n)))))
猜你喜欢
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 2023-04-06
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多