use*_*622 1 r data-manipulation
我有一个data.frame如下
df <- read.table(header = T, text = "Item.Nbr supply demand
1 82078-002 1 1
2 82078-007 2 0
3 82078-007 4 0
4 82078-007 0 0
5 82078-007 0 7")
> df
Item.Nbr supply demand
1 82078-002 1 1
2 82078-007 2 0
3 82078-007 4 0
4 82078-007 0 0
5 82078-007 0 7
Run Code Online (Sandbox Code Playgroud)
我想计算Item.Nbr发生0次供需的次数,我也想知道Item.Nbr供应和需求的次数是多少次.
Item.Nbr 0_supply 0_demand 0_both
1 82078-002 0 0 0
2 82078-007 2 3 1
Run Code Online (Sandbox Code Playgroud)
使用基数R aggregate
:
aggregate(. ~ Item.Nbr, data=transform(df, both=supply+demand), FUN=function(x) sum(x==0) )
#or
aggregate(
cbind(supply,demand,both=supply+demand) ~ Item.Nbr, data=df, FUN=function(x) sum(x==0)
)
# Item.Nbr supply demand both
#1 82078-002 0 0 0
#2 82078-007 2 3 1
Run Code Online (Sandbox Code Playgroud)
或者dplyr
如果那是你的包(向@akrun点头):
df %>%
mutate(both= supply+demand) %>%
group_by(Item.Nbr) %>%
summarise_each(funs(sum(!.)))
#Source: local data frame [2 x 4]
#
# Item.Nbr supply demand both
#1 82078-002 0 0 0
#2 82078-007 2 3 1
Run Code Online (Sandbox Code Playgroud)