Create duplicate rows based on conditions in R
Using dplyr
library("data.table")
library("dplyr")
#data
dt <- data.table(ID = c("A", "A", "B", "B"),
Amount1 = c(100, 200, 300, 400),
Amount2 = c(1500, 1500, 2400, 2400),
Dupl = c(1, 0, 1, 0))
#result
rbind(dt,
dt %>%
filter(Dupl == 1) %>%
mutate(Dupl = 2,
Amount1 = Amount2))
# ID Amount1 Amount2 Dupl
# 1: A 100 1500 1
# 2: A 200 1500 0
# 3: B 300 2400 1
# 4: B 400 2400 0
# 5: A 1500 1500 2
# 6: B 2400 2400 2
You could try
rbind(dt,dt[Dupl==1][,c('Amount1', 'Dupl') := list(Amount2, 2)])