ADD the 2 rows of column if they have same values in other columns

Data i have

id <- c(1,1,1,1,2,2,2,2,3,3,3,4,4)
time <- c(1,2,3,4,1,2,2,3,1,4,4,1,2)
dose <- c(10,20,30,40,30,20,40,10,10,30,70,20,30)
rate <- c(5,6,6,7,3,4,4,6,7,8,9,2,3)

df <- data.frame(id,time,dose,rate)

Data i want

id <- c(1,1,1,1,2,2,2,3,3,3,4,4)
time <- c(1,2,3,4,1,2,3,1,4,4,1,2)
dose <- c(10,20,30,40,30,60,10,10,30,70,20,30)
rate <- c(5,6,6,7,3,4,6,7,8,9,2,3)

df2 <- data.frame(id,time,dose,rate)

I just want add the dose row, if they have same values in id,time,rate.

Please help me to do this. Thank you

This is a standard use of the group_by and summarize functions from dplyr.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
id <- c(1,1,1,1,2,2,2,2,3,3,3,4,4)
time <- c(1,2,3,4,1,2,2,3,1,4,4,1,2)
dose <- c(10,20,30,40,30,20,40,10,10,30,70,20,30)
rate <- c(5,6,6,7,3,4,4,6,7,8,9,2,3)

df <- data.frame(id,time,dose,rate)
df <- df %>% group_by(id,time,rate) %>% summarize(dose=sum(dose))
#> `summarise()` regrouping output by 'id', 'time' (override with `.groups` argument)
df
#> # A tibble: 12 x 4
#> # Groups:   id, time [11]
#>       id  time  rate  dose
#>    <dbl> <dbl> <dbl> <dbl>
#>  1     1     1     5    10
#>  2     1     2     6    20
#>  3     1     3     6    30
#>  4     1     4     7    40
#>  5     2     1     3    30
#>  6     2     2     4    60
#>  7     2     3     6    10
#>  8     3     1     7    10
#>  9     3     4     8    30
#> 10     3     4     9    70
#> 11     4     1     2    20
#> 12     4     2     3    30

Created on 2020-11-28 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.