这是tidyverse 的一个选项。我们通过'ID'获得distinct的数据集行,mutate变量'A','B'为1,'DATEE'为NA,然后将bind_rows行与原始数据集和@987654325绑定@ by '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), ]
# ID DATEE A B
# 1 102984 <NA> 1.0 1.0
# 4 102984 2016-11-23 2.0 2.0
# 2 140349 <NA> 1.0 1.0
# 5 140349 2016-11-23 1.5 1.5
# 3 167109 <NA> 1.0 1.0
# 6 167109 2017-04-16 2.0 2.0
# 7 167109 2017-06-21 1.5 1.5
或者用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)
# 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
还有其他一些方法:
# 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][]