如何在更新输入时重复应用函数
How can you apply a function repeatedly while updating the input
我正在寻找函数式编程解决方案。
如何将一个函数重复应用到一个输入,比方说一个数据框,它在每次迭代中都会更新?
例子
test_df <- tibble(x = c(1, 2, 3, 3),
y = c("10_11", "20_21", "30", "31"),
z = c("1_2_3_4_5", "1_2_3_4_5", "1", "1_2_3_4_5"))
下面的代码按 y 列分隔行,然后按 z 列分隔行。请注意,由于 Error: Incompatible lengths: 2, 5
.
,使用 separate_rows(test_df, y, z, sep = "_")
无效
test_df %>%
separate_rows(y, sep = "_") %>%
separate_rows(z, sep = "_") %>%
print(n=31)
理想情况下,我只想使用 separate_rows
一次。我该怎么做?
for 循环方法可能是:
my_vars <- c("y","z")
for(i in 1:length(my_vars)){
test_df <- separate_rows(test_df, my_vars[i], sep = "_")
}
使用减少:
test_df %>% Reduce(function(...) separate_rows(..., sep = "_"), 2:3, init = .)
给予:
# A tibble: 26 x 3
x y z
<dbl> <chr> <chr>
1 1 10 1
2 1 10 2
3 1 10 3
4 1 10 4
5 1 10 5
6 1 11 1
7 1 11 2
8 1 11 3
9 1 11 4
10 1 11 5
# ... with 16 more rows
来自 purrr 的 reduce
也可以工作(切换前两个参数并使用 .init 而不是 init )但在这里没有真正的优势。
我正在寻找函数式编程解决方案。
如何将一个函数重复应用到一个输入,比方说一个数据框,它在每次迭代中都会更新?
例子
test_df <- tibble(x = c(1, 2, 3, 3),
y = c("10_11", "20_21", "30", "31"),
z = c("1_2_3_4_5", "1_2_3_4_5", "1", "1_2_3_4_5"))
下面的代码按 y 列分隔行,然后按 z 列分隔行。请注意,由于 Error: Incompatible lengths: 2, 5
.
separate_rows(test_df, y, z, sep = "_")
无效
test_df %>%
separate_rows(y, sep = "_") %>%
separate_rows(z, sep = "_") %>%
print(n=31)
理想情况下,我只想使用 separate_rows
一次。我该怎么做?
for 循环方法可能是:
my_vars <- c("y","z")
for(i in 1:length(my_vars)){
test_df <- separate_rows(test_df, my_vars[i], sep = "_")
}
使用减少:
test_df %>% Reduce(function(...) separate_rows(..., sep = "_"), 2:3, init = .)
给予:
# A tibble: 26 x 3
x y z
<dbl> <chr> <chr>
1 1 10 1
2 1 10 2
3 1 10 3
4 1 10 4
5 1 10 5
6 1 11 1
7 1 11 2
8 1 11 3
9 1 11 4
10 1 11 5
# ... with 16 more rows
来自 purrr 的 reduce
也可以工作(切换前两个参数并使用 .init 而不是 init )但在这里没有真正的优势。