如果满足某些条件,则计算行数

Counting number of rows if certain conditions are met

我确定有人对此问题有聪明的解决方案:

我有一个这样的数据框:

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

如果满足某些条件,我想通过计算行数来获得四个值:

我怀疑这可以通过某种 If/Else 语句结合“table(sign...”命令来实现?

试试这个:

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

我们可以在 sign

上创建带有 interaction 的列后使用 count
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