【问题标题】:Replace values to row above based on condition根据条件将值替换到上面的行
【发布时间】:2019-03-23 10:12:51
【问题描述】:

我想根据以下条件将值替换到上面的行:

如果 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 中做到这一点?非常感谢您的帮助!

【问题讨论】:

    标签: r replace data-manipulation data-cleaning


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 2023-04-03
      相关资源
      最近更新 更多