【发布时间】:2020-01-18 16:53:11
【问题描述】:
我有一个名为sections 的小标题/数据框,我想用它来创建几个新的小标题/数据框。我想遍历每一行并为每一行创建一个新的小标题。第一列提供新 tibble 的名称,第二列和第三列提供在另一个名为 my_text 的 tibble 上使用的索引。
sections <- structure(list(sections = c("cash_and_bank_sweep", "money_market_funds_non-sweep",
"equities"),
begin_row = c(325L, 345L, 357L),
end_row = c(345L, 357L, 384L)),
class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA, -3L))
> sections
# A tibble: 3 x 3
sections begin_row end_row
<chr> <int> <int>
1 cash_and_bank_sweep 325 345
2 money_market_funds_non-sweep 345 357
3 equities 357 384
set.seed(1)
my_text <- tibble(Strings = sample(letters, size = 1000, replace = TRUE)
> head(my_text)
# A tibble: 6 x 1
Strings
<chr>
1 y
2 d
3 g
4 a
5 b
6 w
所以我想创建的第一个小标题是cash_and_bank_sweep。手动我可以创建如下:
cash_and_bank_sweep <- tibble(Strings = my_text$Strings[sections$begin_row[1]:sections$end_row[1]])
> head(cash_and_bank_sweep)
# A tibble: 6 x 1
Strings
<chr>
1 e
2 n
3 e
4 k
5 k
6 q
有没有办法通过循环或其他结构有效地做到这一点?
【问题讨论】: