tidyverse. distinct : 'ID', mutate 'A', 'B' 1 'DATEE' NA, bind_rows arrange 'ID'
library(tidyverse)
df1 %>%
distinct(ID, .keep_all= TRUE) %>%
mutate_at(vars("A", "B"), funs((1))) %>%
mutate(DATEE = NA) %>%
bind_rows(., df1) %>%
arrange(ID)
# ID DATEE A B
#1 102984 <NA> 1.0 1.0
#2 102984 2016-11-23 2.0 2.0
#3 140349 <NA> 1.0 1.0
#4 140349 2016-11-23 1.5 1.5
#5 167109 <NA> 1.0 1.0
#6 167109 2017-04-16 2.0 2.0
#7 167109 2017-06-21 1.5 1.5
( , , , df1$DATEE = as.Date(df1$DATEE).)
R:
new1 = data.frame(ID = unique(df1$ID), DATEE = Sys.Date()[NA_integer_], A = 1, B = 1)
tabs = list(new1, df1)
res = do.call(rbind, tabs)
res <- res[order(res$ID), ]
data.table:
library(data.table)
new1 = data.table(ID = unique(df1$ID), DATEE = Sys.Date()[NA_integer_], A = 1, B = 1)
tabs = list(new1, df1)
res = rbindlist(tabs)
setorder(res)
:
# or let DATEE and other cols be filled as NA
library(data.table)
new1 = data.table(ID = unique(df1$ID), A = 1, B = 1)
tabs = list(df1, new1)
res = rbindlist(tabs, fill = TRUE, idcol = "src")
setorder(res, ID, -src)
res[, src := NULL ]
# or a more compact option (assuming df1$A has no missing values)
library(data.table)
setDT(df1)[, .SD[c(.N+1, seq_len(.N))], ID][is.na(A), c("A", "B") := 1][]