假设我们有,
library(data.table)
dt <- data.table(id = 1:4, x1 = 10:13, x2=21:24, wt=c(1,0,0.5,0.7))
返回,
id x1 x2 wt
1: 1 10 21 1.0
2: 2 11 22 0.0
3: 3 12 23 0.5
4: 4 13 24 0.7
我想在以下条件下复制观察结果:
- 如果
wt
为 0 或 1,我们将flag
分别分配为 1 和 0 - 如果 0 <
wt
< 1,我们将flag
指定为 0。此外,我们使用wt = 1-wt
复制此观察结果并将flag
指定为 1。
我期望的返回是
id x1 x2 wt flag
1: 1 10 21 1.0 0
2: 2 11 22 0.0 1
3: 3 12 23 0.5 0
4: 3 12 23 0.5 1
5: 4 13 24 0.7 0
6: 4 13 24 0.3 1
我已经尝试过我的代码
dt[,flag:=ifelse(wt==1,0, ifelse(wt==0, 1, 0))]
dt[,freq:=ifelse(wt > 0 & wt < 1, 2, 1)]
dtr <- dt[rep(1:.N, freq)][,Indx:=1:.N, by = id]
dtr[freq==2&Indx==2, wt:=1-wt]
dtr[Indx==2,flag:=1]
dtr[,`:=`(freq=NULL, Indx=NULL)]
但是,我认为这效率不高。
你有什么建议吗?
最佳答案
这是一种使用数据框的方法:
dt <- data.frame(id = 1:4, x1 = 10:13, x2=21:24, wt=c(1,0,0.5,0.7))
# create the flag column
dt$flag = 1 - ceiling(dt$wt)
#create a new data frame with the rows that fulfill condition 2
dt2 = dt[dt$wt < 1 && dt$wt > 0, ]
dt2$wt = 1 - dt2$wt
dt2$flag = 1
#rbind it to the original data frame and reorder by id
dt = rbind(dt,dt2)
dt = dt[order(dt$id),]
结果:
id x1 x2 wt flag
1 1 10 21 1.0 0
2 2 11 22 0.0 1
3 3 12 23 0.5 0
31 3 12 23 0.5 1
4 4 13 24 0.7 0
41 4 13 24 0.3 1
关于r - 如何根据权重复制观察结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40902512/