Marcusson
Marcusson

Reputation: 17

Sum positive and negative values grouped by other values

Using this data:

 Respon    Type     Value
   Mark     -1        2
   Mark     -2        4
   Sheyla    1        10
   Ana       1        4
   Sheyla    2        3
   Mark      1        4
   Ana      -2        6
   Ana       2        7

I would like to get two columns named "positive" and "negative" which sums positive and negative values depending on type and grouped by Respon

Respon    Positive     Negative
 Mark         4           6
 Sheyla       13          0
 Ana          11          6           

Upvotes: 0

Views: 2321

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

With base R xtabs we can group Value on Respon and signed Type variable.

xtabs(Value~Respon + sign(Type), df)

#       sign(Type)
#  Respon   -1  1
#  Ana       6 11
#  Mark      6  4
#  Sheyla    0 13

Upvotes: 0

akrun
akrun

Reputation: 887108

We can use

library(dplyr)
df1 %>% 
    group_by(Respon)  %>% 
    summarise(Positive = sum(Value[Type>0]), Negative = sum(Value[Type <0]))
# A tibble: 3 × 3
#  Respon Positive Negative
#   <chr>    <int>    <int>
#1    Ana       11        6
#2   Mark        4        6
#3 Sheyla       13        0

Or using data.table

library(data.table)
dcast(setDT(df1), Respon ~ sign(Type), value.var = "Value", sum)

Upvotes: 2

Related Questions