[英]dplyr - apply a custom function using rowwise()
I have a data frame and want to count the number of zeros in each row using dplyr's rowwise. 我有一个数据框,并希望使用dplyr的行数计算每一行中的零个数。 What am I doing wrong?
我究竟做错了什么?
dt2 = data.frame(A = c(8, 6), B = c(0, 0), C = c(0, 5))
dt2
zerocount <- function(x) {sum(x == 0)}
library(dplyr)
dt2 %>% rowwise() %>% mutate(nr_of_0s = zerocount(A, B, C))
The code above works if I replace zerocount(A, B, C) in the line above with, for example, max(A, B, C). 如果我用例如max(A,B,C)替换上一行中的zerocount(A,B,C),则上面的代码有效。 What is wrong?
怎么了? Thank you!
谢谢!
I don't think your problem is with rowwise. 我认为您的问题不在于按行。 The way your function is written, it's expecting a single object.
函数的编写方式,期望有一个对象。 Try adding ac():
尝试添加ac():
dt2 %>% rowwise() %>% mutate(nr_of_0s = zerocount(c(A, B, C)))
Note that, if you aren't committed to using your own function, you can skip rowwise entirely, as Nettle also notes. 请注意,如果您不打算使用自己的函数,则可以像Nettle一样完全跳过按行。
rowSums
already treats data frames in a rowwise fashion, which is why this works: rowSums
已经按行方式处理数据帧,这就是为什么这样做的原因:
dt2 %>% mutate(nr_of_0s = rowSums(. == 0))
A logical test for the presence of zeros would look like: 逻辑测试是否为零看起来像:
dt2==0
A B C
[1,] FALSE TRUE TRUE
[2,] FALSE TRUE FALSE
Sum the number of Trues by row 按行求和的总数
rowSums(dt2==0)
[1] 2 1
With this in mind, here's a tidyverse solution: 考虑到这一点,这是一个整洁的解决方案:
dt2 %>%
mutate(zero.count = rowSums(.==0) ) #<The dot is shorthand for dt2
A B C zero.count
1 8 0 0 2
2 6 0 5 1
Another method without using rowwise()
: 不使用
rowwise()
另一种方法:
mutate(dt2, zero_count = pmap_int(dt2, function(...) sum(c(...) == 0)))
> A B C zero_count
> 1 8 0 0 2
> 2 6 0 5 1
pmap()
is a purrr
function that takes takes elements from a list (which in this case is the data frame) and applies a function. pmap()
是一个purrr
函数,它从列表(在本例中为数据帧)中获取元素并应用一个函数。 In this case, I'm just applying your function on the fly. 在这种情况下,我只是即时应用您的功能。 By default,
pmap()
returns a list, but using the _int
suffix makes it return an integer vector. 默认情况下,
pmap()
返回一个列表,但是使用_int
后缀使其返回整数向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.