简体   繁体   中英

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?

Try this:

library(dplyr)

df_count <- df %>% summarise(con1 = sum(B < 0 & C < 0), 
                             con2 = sum(B > 0 & C > 0),
                             con3 = sum(B < 0 & C > 0),
                             con4 = sum(B > 0 & C < 0))

df_count
con1 con2 con3 con4
   2    2    0    2

We can use count after creating a column with interaction on the sign

library(dplyr)
df %>%
   transmute(con = factor(interaction(sign(B), sign(C), sep=" "), 
     levels = c('1 1', '1 -1', '-1 1', '-1 -1'))) %>%
   count(con, .drop = FALSE)
#    con n
#1   1 1 2
#2  1 -1 2
#3  -1 1 0
#4 -1 -1 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM