Andraž Poje Andraž Poje - 2 months ago 5
R Question

Combining specific row data in R

Hi I have a dataset where one row presents a item in an order. One order can have more items and therefore more rows in a dataset.

data looks like:

code nr. Of items
1 252222016 5
3 252812016 1
5 252812016 1
6 253012016 1
12 253042016 20
13 253042016 20
15 253052016 1
16 253072016 3
18 253082016 4


I would like a result where I would summ the "nr. Of items" where there is a same "code" and write the resoult in the row. if one order has more items I would like to have a resoult written in the last row of an order and previous rows would be NAs.

how I want the final solution to look like:

code nr. Of items result
1 252222016 5 5
3 252812016 1 na
5 252812016 1 2
6 253012016 1 1
12 253042016 20 na
13 253042016 20 40
15 253052016 1 1
16 253072016 3 3
18 253082016 4 4


I would appreciate the help!

Answer

Another dplyr alternative, using ifelse and fromLast = TRUE:

library(dplyr)

df1 <- df1 %>% 
  group_by(code) %>% 
  mutate(result = ifelse(duplicated(code, fromLast = TRUE), NA, sum(nr.Of.items)))