根据 R 中的列用新条目更新大型数据框?

Update large dataframe with new entry according to the columns in R?

我有一个大数据框(50 多列)。 我以不同的列顺序获取每一行,我需要向数据框添加一个新行,但是这个新行应该更新正确的列。

比如我有一个df:

col1 col2 col3 col4 col5 col6 col7 col8 col9  col10 .........
1    a    Don  Lu   854  W    eee  1    1234  yes 
4    s34  Dino Ken  44   S    aaa  1    3432  no
5    1ee  Pupu Dar  2215 R    bbb  -4   12121 yes

我得到一个新条目:

col6 col2 col5 col4 col3 col1 col7 col10 col9  col8 .........
R    re3  666  Rino Pino 33   ddd  no    55874 6

我考虑过 dplyr 按名称将函数排列到 arrange 并更新, 我也可以使用 $ 更新每一个,请告知最佳做法是什么?

我认为您可以只使用 merge() 并将参数 all 设置为 TRUE。尝试

df <- read.table(text = "col1 col2 col3 col4 col5 col6 col7 col8 col9  col10
                 1    a    Don  Lu   854  W    eee  1    1234  yes 
                 4    s34  Dino Ken  44   S    aaa  1    3432  no
                 5    1ee  Pupu Dar  2215 R    bbb  -4   12121 yes", header=TRUE)
new.entry <- read.table(text = "col6 col2 col5 col4 col3 col1 col7 col10 col9  col8
                                R    re3  666  Rino Pino 33   ddd  no    55874 6", header = TRUE)

merge(df, new.entry, all = TRUE)
#  col1 col2 col3 col4 col5 col6 col7 col8  col9 col10
#    1    a  Don   Lu  854    W  eee    1  1234   yes
#    4  s34 Dino  Ken   44    S  aaa    1  3432    no
#    5  1ee Pupu  Dar 2215    R  bbb   -4 12121   yes
#   33  re3 Pino Rino  666    R  ddd    6 55874    no

假设您的新条目是 data.frame() 并称为 df1,我会使用 data.table 包中的 rbindlist()

merged <- list(df, df1)
rbindlist(merged, fill = TRUE)

很快就会完成这项工作。事实上,您可以在 list

中放入任意多的条目
merged <- list(df1, df2, ...... , df99999, df100000)
rbindlist(merged, fill = TRUE)

做起来很快。

请注意 df1 中不在 df 中的任何条目,反之亦然 NA

来自 dplyr 的

bind_rows() 也应该有效。

data <- data.frame(x = rep("ABC", 3), y = 1, z = 0)
data1 <- data.frame(y = 2, x = rep("XX", 4))
datax <- bind_rows(data, data1)