2017-02-14 60 views
-1

使用該數據分組總和正值和負值:其他值

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 

我想獲得一個名爲取決於類型「積極」和「消極」至極資金正值和負值,並通過分組兩列Respon

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

謝謝你在前進,

+0

in base R:'reshape(aggregate(Value_Response + sign(Type),df,FUN =「sum」),idvar =「Respon」,timevar =「sign(Type)」,direction = 「寬」)' –

回答

1

我們可以使用

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 

或者用data.table

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

隨着Respon基礎R xtabs我們可以組Value並簽署Type變量。

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

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