Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count logical values through multiple columns in R?

Tags:

r

dplyr

My goal is to count the total number of tasks each person (variable = name) has done. One person can do only one task per day.

My dataset looks like this:

name  task1 task2 task3 day
bill  TRUE  FALSE FALSE  1
bill  FALSE TRUE  FALSE  2
bill  FALSE FALSE FALSE  3
bill  NA    NA    NA     4
alex  FALSE FALSE FALSE  1
alex  TRUE  FALSE FALSE  2
alex  FALSE FALSE FALSE  3
alex  NA    NA     NA    4
rob   TRUE  FALSE FALSE  1
rob   TRUE  FALSE FALSE  2
rob   TRUE  FALSE FALSE  3
rob   NA    NA    NA     4

This is the output that I need:

name  total
bill   2
alex   1    
rob    3

My code: (As you can see I can summarise the number of tasks, but the output is still far away from what I need)

total <- sum1%>%
group_by(`name`)%>%
summarise(task1_processed=sum(task11, na.rm = TRUE), task2_processed = sum(task2, na.rm = TRUE),
               task3_processed = sum(task3, na.rm = TRUE))
like image 302
San Avatar asked Nov 24 '25 11:11

San


1 Answers

For each name you can sum the 'task' columns together.

library(dplyr)
df %>%
  group_by(name) %>%
  summarise(total = sum(unlist(select(cur_data(), starts_with('task'))), na.rm = TRUE))

#   name  total
#* <chr> <int>
#1 alex      1
#2 bill      2
#3 rob       3
like image 86
Ronak Shah Avatar answered Nov 26 '25 03:11

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!