使用 pmap 遍历 tibble 的行 [英] Using pmap to iterate over rows of a tibble
问题描述
我有一个非常简单的 tibble,我想遍历它的行以使用 pmap
函数应用一个函数.我想我可能误解了 pmap
函数的一些要点,但我在选择参数时遇到了困难.所以我想知道在这种情况下我是否应该将 rowwise
函数与 pmap
一起使用.不过我没见过案例.另一个问题是使用列表或 select
函数选择要迭代的变量:
I have a very simple tibble and I would like to iterate over its rows to apply a function using pmap
function. I think I may have misinterpreted some points on pmap
function but I mostly have difficulty selecting arguments. So
I would like to know whether I should use rowwise
function in this case with pmap
or not. However I haven't seen a case.
The other problem is the selection of variables to iterate over using list or select
function:
# Here is my tibble
# Imagine I would like to apply a `n_distinct` function with pmap on it every rows
df <- tibble(id = c("01", "02", "03","04","05","06"),
A = c("Jan", "Mar", "Jan","Jan","Jan","Mar"),
B = c("Feb", "Mar", "Jan","Jan","Mar","Mar"),
C = c("Feb", "Mar", "Feb","Jan","Feb","Feb")
)
# It is perfectly achievable with `rowwise` and `mutate` and results in my desired output
df %>%
rowwise() %>%
mutate(overal = n_distinct(c_across(A:C)))
# A tibble: 6 x 5
# Rowwise:
id A B C overal
<chr> <chr> <chr> <chr> <int>
1 01 Jan Feb Feb 2
2 02 Mar Mar Mar 1
3 03 Jan Jan Feb 2
4 04 Jan Jan Jan 1
5 05 Jan Mar Feb 3
6 06 Mar Mar Feb 2
# But with `pmap` it won't.
df %>%
select(-id) %>%
mutate(overal = pmap_dbl(list(A, B, C), n_distinct))
# A tibble: 6 x 4
A B C overal
<chr> <chr> <chr> <dbl>
1 Jan Feb Feb 1
2 Mar Mar Mar 1
3 Jan Jan Feb 1
4 Jan Jan Jan 1
5 Jan Mar Feb 1
6 Mar Mar Feb 1
我只需要对 pmap
在 tibbles 上按行迭代的应用做一些解释,所以我非常感谢您提前提供的帮助,谢谢.
I just need a little bit of explanation on the application of pmap
for rowwise iteration on tibbles, so I highly appreciate any help in advance, thank you.
推荐答案
我能够追踪到问题,但在这里无法确定它是错误还是功能.关键是 pmap
中的 n_distinct()
将给定的输入处理为具有 3 列的数据框.将 n_distinct()
应用于数据帧时,它计算不同行的数量,因此每行中的 1
I was able to track down the issue yet cannot say whether it's a bug or a feature here. The point is that n_distinct()
inside pmap
handles the given input as a data frame with 3 columns. When applying n_distinct()
to a data frame it counts the number of distinct rows, hence the 1 in each row
n_distinct(tibble(a = c(1, 2, 2),
b = 3))
#> [1] 2
诀窍是先将输入转换为向量,然后将其传递给 n_distinct
The trick is to convert the input to a vector first and then pass it to n_distinct
df %>%
select(-id) %>%
mutate(overal = pmap_dbl(list(A, B, C), ~ n_distinct(c(...))))
#> # A tibble: 6 x 4
#> A B C overal
#> <chr> <chr> <chr> <dbl>
#> 1 Jan Feb Feb 2
#> 2 Mar Mar Mar 1
#> 3 Jan Jan Feb 2
#> 4 Jan Jan Jan 1
#> 5 Jan Mar Feb 3
#> 6 Mar Mar Feb 2
这篇关于使用 pmap 遍历 tibble 的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!