I have a data frame and want to count the number of zeros in each row using dplyr's rowwise. 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). 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 a c():
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. rowSums
already treats data frames in a rowwise fashion, which is why this works:
dt2 %>% mutate(nr_of_0s = rowSums(. == 0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With