gpt4 book ai didi

R - 合并和更新主数据集

转载 作者:行者123 更新时间:2023-12-04 10:11:06 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to use merge or replace to update a table in R with multiple columns

(4 个回答)


5年前关闭。




所以,我有两个数据集代表旧地址和当前地址。

> main
idspace id x y move
198 1238 33 4 stay
641 1236 36 12 move
1515 1237 30 28 move

> move
idspace id x y move
4 1236 4 1 move

我需要的是将新数据( move )与旧数据( main )合并并更新 main一旦合并。

我想知道是否有可能在一次手术中完成?

更新基于 id , 这是个人标识符。
idspace , x , y是位置ID。

所以,我需要的输出是
> main
idspace id x y move
198 1238 33 4 stay
4 1236 4 1 move # this one is updated
1515 1237 30 28 move

我不知道我怎么能做到这一点。

就像是
merge(main, move, by = c('id'), all = T, suffixes = c('old', 'new'))

但是,这是错误的,因为我需要手动进行如此多的操作。

任何解决方案?

数据
> dput(main)
structure(list(idspace = structure(c(2L, 3L, 1L), .Label = c("1515",
"198", "641"), class = "factor"), id = structure(c(3L, 1L, 2L
), .Label = c("1236", "1237", "1238"), class = "factor"), x = structure(c(2L,
3L, 1L), .Label = c("30", "33", "36"), class = "factor"), y = structure(c(3L,
1L, 2L), .Label = c("12", "28", "4"), class = "factor"), move = structure(c(2L,
1L, 1L), .Label = c("move", "stay"), class = "factor")), .Names = c("idspace",
"id", "x", "y", "move"), row.names = c(NA, -3L), class = "data.frame")

> dput(move)
structure(list(idspace = structure(1L, .Label = "4", class = "factor"),
id = structure(1L, .Label = "1236", class = "factor"), x = structure(1L, .Label = "4", class = "factor"),
y = structure(1L, .Label = "1", class = "factor"), move = structure(1L, .Label = "move", class = "factor")), .Names = c("idspace",
"id", "x", "y", "move"), row.names = c(NA, -1L), class = "data.frame")`

最佳答案

使用data.table的join+update功能:

require(data.table) # v1.9.6+
setDT(main) # convert data.frames to data.tables by reference
setDT(move)

main[move, on=c("id", "move"), # extract the row number in 'main' where 'move' matches
c("idspace", "x", "y") := .(i.idspace, i.x, i.y)] # update cols of 'main' with
# values from 'i' = 'move' for
# those matching rows


main
# idspace id x y move
# 1: 198 1238 33 4 stay
# 2: 4 1236 4 1 move
# 3: 1515 1237 30 28 move

此更新 main到位。

关于R - 合并和更新主数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39070174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com