根据条件将值替换为上面的行
Replace values to row above based on condition
我想根据以下条件将值替换为上面的行:
如果pc_no = DELL,将pc_no和cust_id的值赋值到event_rep和loc_id的上一行。
之后要删除具有 "DELL" 的行。
id pc_no cust_id event_id event_date event_mark event_rep loc_id
1 51 NA CC 2018-08-15 SE NA NA
2 DELL IBM NA 2018-08-16 SC NA NA
3 53 NA CC 2018-08-17 SD UNK SUW
4 54 NA CC 2018-08-18 SF UNK NA
5 DELL ACER CC 2018-08-19 SV UNK NA
I.E应该是这样的:
id pc_no cust_id event_id event_date event_mark event_rep loc_id
1 51 NA CC 2018-08-15 SE DELL IBM
3 53 NA CC 2018-08-17 SD UNK SUW
4 54 NA CC 2018-08-18 SF DELL ACER
我如何在 R 中做到这一点?非常感谢您的帮助!
Base R 解决方案
#Get indices of rows to where pc_no = DELL
inds <- which(df$pc_no == "DELL")
#Get values from pc_no and cust_id and assign it to previous row
df[inds - 1, c("event_rep", "loc_id")] <- df[inds, c("pc_no", "cust_id")]
#Remove the rows
df1 <- df[-inds, ]
df1
# id pc_no cust_id event_id event_date event_mark event_rep loc_id
#1 1 51 <NA> CC 2018-08-15 SE DELL IBM
#3 3 53 <NA> CC 2018-08-17 SD UNK SUW
#4 4 54 <NA> CC 2018-08-18 SF DELL ACER
我想根据以下条件将值替换为上面的行:
如果pc_no = DELL,将pc_no和cust_id的值赋值到event_rep和loc_id的上一行。 之后要删除具有 "DELL" 的行。
id pc_no cust_id event_id event_date event_mark event_rep loc_id
1 51 NA CC 2018-08-15 SE NA NA
2 DELL IBM NA 2018-08-16 SC NA NA
3 53 NA CC 2018-08-17 SD UNK SUW
4 54 NA CC 2018-08-18 SF UNK NA
5 DELL ACER CC 2018-08-19 SV UNK NA
I.E应该是这样的:
id pc_no cust_id event_id event_date event_mark event_rep loc_id
1 51 NA CC 2018-08-15 SE DELL IBM
3 53 NA CC 2018-08-17 SD UNK SUW
4 54 NA CC 2018-08-18 SF DELL ACER
我如何在 R 中做到这一点?非常感谢您的帮助!
Base R 解决方案
#Get indices of rows to where pc_no = DELL
inds <- which(df$pc_no == "DELL")
#Get values from pc_no and cust_id and assign it to previous row
df[inds - 1, c("event_rep", "loc_id")] <- df[inds, c("pc_no", "cust_id")]
#Remove the rows
df1 <- df[-inds, ]
df1
# id pc_no cust_id event_id event_date event_mark event_rep loc_id
#1 1 51 <NA> CC 2018-08-15 SE DELL IBM
#3 3 53 <NA> CC 2018-08-17 SD UNK SUW
#4 4 54 <NA> CC 2018-08-18 SF DELL ACER