Reputation: 2251
I want to make a summary by ID, DRUG, FED summarising the sum of the CONC
for DVID =1
and DVID==2
df<-
ID DRUG FED DVID CONC
1 1 1 1 20
1 1 1 2 40
2 2 0 1 30
2 2 0 2 100
I tried using this:
df2 <- df %>%
group_by(ID,DRUG,FED) %>%
summarise(SumCOnc=CONC+lag(CONC))
However I am getting this error:
Error: expecting a single value
I don't get the error when I use mutate
. Is there a way to go around it so I use summarise
in the case described above?
The output should basically be this:
ID DRUG FED SumConc
1 1 1 60
2 2 0 130
Upvotes: 3
Views: 7353
Reputation: 886938
Or from data.table
library(data.table)
setDT(df)[, .(SumConc = sum(CONC)), .(ID, DRUG, FED)]
# ID DRUG FED SumConc
#1: 1 1 1 60
#2: 2 2 0 130
Upvotes: 4
Reputation: 388797
A simple Base R approach would be using aggregate
aggregate(CONC ~ ID + DRUG + FED, df, sum)
# ID DRUG FED CONC
#1 2 2 0 130
#2 1 1 1 60
Upvotes: 4
Reputation: 226057
This seems pretty straightforward: just use sum()
, don't mess around with lag()
...
Get data:
df<- read.table(header=TRUE,
text="
ID DRUG FED DVID CONC
1 1 1 1 20
1 1 1 2 40
2 2 0 1 30
2 2 0 2 100
")
Process:
library(dplyr)
df %>%
group_by(ID,DRUG,FED) %>%
summarise(SumConc=sum(CONC))
## ID DRUG FED SumConc
## 1 1 1 1 60
## 2 2 2 0 130
Upvotes: 6