【发布时间】: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 列,每列命名为col1、col2、...col100?我不在乎里面是什么!
【问题讨论】:
-
听起来像是 R 中的
Reduce操作,虽然它不在 tibble 世界中,但它确实给出了相同的值:-set.seed(1); Reduce(`+`, replicate(5,list(sample(10))), accumulate=TRUE) -
或者如果你更熟悉tidyverse中的purrr,那么
accumulate(rerun(5, sample(10)), `+`)