Reputation: 99
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:
Im suspecting that this can be achieved with some sort of If/Else statement, combined with the "table(sign..." command?
Upvotes: 0
Views: 1696
Reputation: 887881
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
Upvotes: 0
Reputation: 2485
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
Upvotes: 2