Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr - apply a custom function using rowwise()

Tags:

r

dplyr

rowwise

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!

like image 688
user3245256 Avatar asked Oct 16 '25 15:10

user3245256


1 Answers

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))
like image 95
benc Avatar answered Oct 18 '25 08:10

benc