I'm looking for R's version of Excel's "COUNTIFS" function to find the number of direct reports for a specific employee based on if they are a manager. I have tried the group-by function and the length function but cannot find the get the correct output. A simple version of my data looks like this:
- employee: a,b,c,d,e,f,g,h
- manager: g,a,a,a,b,b,e,c
Where the output should look like this:
- direct report: 3,2,1,0,1,0,0,0
CodePudding user response:
table(factor(manager, employee))
a b c d e f g h
3 2 1 0 1 0 1 0
CodePudding user response:
To do a COUNTIF you can simply sum up the result of a comparison. In this case you say sum(manager == "a")
. manager == "a"
will give a vector
#> [1] FALSE TRUE TRUE TRUE FALSE FALSE FALSE FALSE
if you sum that up R will coerce the boolean to integers so that each TRUE will add 1 to the sum.
In your case we need sapply
to repeat this step for each element of employee
(my guess is, the 7 element in your "direct report" example should be 1 instead of 0).
employee <- letters[1:8]
manager <- c("g","a","a","a","b","b","e","c")
sapply(employee, function(x) sum(manager == x))
#> a b c d e f g h
#> 3 2 1 0 1 0 1 0
Created on 2022-06-21 by the reprex package (v2.0.1)