【问题标题】:Update rows of data frame in R更新R中的数据框行
【发布时间】:2015-12-30 05:11:06
【问题描述】:

假设我从一个数据框开始:

 ID Measurement1 Measurement2
  1           45          104
  2           34           87
  3           23           99
  4           56           67
...

然后我有第二个数据框,用于更新第一个中的记录:

 ID Measurement1 Measurement2
  2           10           11
  4           21           22

我如何使用 R 来结束:

 ID Measurement1 Measurement2
  1           45          104
  2           10           11
  3           23           99
  4           21           22
...

现实中的数据框是非常大的数据集。

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用match 来获取行索引。使用该索引对行进行子集化,我们将第一个数据集的第二和第三列替换为第二个数据集的相应列。

    ind <- match(df2$ID, df1$ID)
    df1[ind, 2:3] <- df2[2:3]
    df1
    #  ID Measurement1 Measurement2
    #1  1           45          104
    #2  2           10           11
    #3  3           23           99
    #4  4           21           22
    

    或者我们可以使用data.table 将数据集on 加入'ID' 列(将第一个数据集转换为'data.table' 即setDT(df1)),并将'Cols' 分配给'iCols ' 来自第二个数据集。

     library(data.table)#v1.9.6+
     Cols <- names(df1)[-1]
     iCols <- paste0('i.', Cols)
     setDT(df1)[df2, (Cols) := mget(iCols), on= 'ID'][]
     #   ID Measurement1 Measurement2
     #1:  1           45          104
     #2:  2           10           11
     #3:  3           23           99
     #4:  4           21           22
    

    数据

    df1 <- structure(list(ID = 1:4, Measurement1 = c(45L, 34L, 23L, 56L), 
    Measurement2 = c(104L, 87L, 99L, 67L)), .Names = c("ID", 
    "Measurement1", "Measurement2"), class = "data.frame",
     row.names = c(NA, -4L))
    
    df2 <-  structure(list(ID = c(2L, 4L), Measurement1 = c(10L, 21L),
     Measurement2 = c(11L, 
     22L)), .Names = c("ID", "Measurement1", "Measurement2"),
     class = "data.frame", row.names = c(NA, -2L))
    

    【讨论】:

      【解决方案2】:
      library(dplyr)
      
      df1 %>%
        anti_join(df2, by = "ID") %>%
        bind_rows(df2) %>%
        arrange(ID)
      

      【讨论】:

        【解决方案3】:

        dplyr 1.0.0 引入了一系列受 SQL 启发的用于修改行的函数。在这种情况下,您现在可以使用rows_update()

        library(dplyr)
        
        df1 %>%
          rows_update(df2, by = "ID")
        
          ID Measurement1 Measurement2
        1  1           45          104
        2  2           10           11
        3  3           23           99
        4  4           21           22
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-18
          • 1970-01-01
          • 2016-05-05
          • 2021-08-25
          相关资源
          最近更新 更多