mardi 2 février 2021

Counting number of rows if certain conditions are met

Im sure someone has a smart solution for this problem:

I have a dataframe like so:

A <- c("name1", "name2", "name3", "name4", "name5", "name6")
B <- c(10, 8, 7, 3, -1, -2)
C <- c(8, 3, -1, -10, -2, -2)
df <- data.frame(A, B, C)
df

      A  B   C
1 name1 10   8
2 name2  8   3
3 name3  7  -1
4 name4  3 -10
5 name5 -1  -2
6 name6 -2  -2

I want to obtain four values, by counting the rows if certain conditions are met:

  • I want to count the number of rows in this dataframe where both B and C are negative integers (>0) -- for this example that would be "2"
  • I want to count the number of rows in this dataframe where both B and C are positive integers (<0)-- for this example that would be "2"
  • I want to count the number of rows in this dataframe where B is a negative integer (>0) and C is positive -- for this example that would be "0"
  • I want to count the number of rows in this dataframe where B is a postive integer and C is negative) -- for this example that would be "2"

Im suspecting that this can be achieved with some sort of If/Else statement, combined with the "table(sign..." command?

Aucun commentaire:

Enregistrer un commentaire