R 将一个数据帧的列中的值替换为另一个数据帧中的值
我试图找到这个问题的解决方案,我有两个数据帧,一个像R 将一个数据帧的列中的值替换为另一个数据帧中的值,r,dataframe,R,Dataframe,我试图找到这个问题的解决方案,我有两个数据帧,一个像 DF1 faID uID 1 20909 1 6661 1 1591 1 28065 1 42783 1 3113 1 21647 1 3825 2 134766 2 271168 2 16710 2 4071608 2 2046526 2 5081272 另一个数据框是这样的 DF2 uID user_cent_w
DF1
faID uID
1 20909
1 6661
1 1591
1 28065
1 42783
1 3113
1 21647
1 3825
2 134766
2 271168
2 16710
2 4071608
2 2046526
2 5081272
另一个数据框是这样的
DF2
uID user_cent_w
1591 15844
42783 466
21647 1514
29695 13958
94120 3615
83098 128
138776 709
90352 991
115384 8039
74483 128
我想在DF1
中添加一个新列user\u cent
,该列的值与DF2
中的uID
的值匹配,或者用DF2
中的user\u cent\w
的值替换DF1
中的uID
的值,即。,如果DF1
的uID
与DF2
的值匹配,即user\u-cent\u-w
则用user\u-cent\u-w
值替换uID
我已经试过了
但这将替换faID
的值以及DF1
中的值
我的预期输出如下所示:
faID user_cent_w
1 15844
1 466
1 1514
1 13958
1 3615
1 128
1 709
1 991
1 8039
1 128
1 6489
1 1781
2 5735
2 2072
2 128
2 128
2 2304
2 9301
2 1282
尝试:
虽然这个老问题已经有了公认的答案,但为了完整起见,我想添加两个
data.table
解决方案
第一个创建一个新对象
library(data.table)
# coerce to data.table and right join on uID
result <- setDT(DF2)[setDT(DF1), on = "uID"][
# replace uID by user_cent_w where available, remove column
!is.na(user_cent_w), uID := user_cent_w][, -"user_cent_w"]
result
第二个在连接时就地更新DF1
,避免复制对象以节省内存和时间:
setDT(DF1)[setDT(DF2), on = "uID", uID := ifelse(is.na(user_cent_w), uID, user_cent_w)]
DF1
资料
DF1能否显示预期的输出merge(DF1,df2,by=“uID”,all.x=TRUE)
;这与您希望实现的目标接近吗?是的,它在merge和@akrun可能的解决方案中都有效。感谢您在很长一段时间后意识到这是一个小问题,即变量(faID)的某些值与(uID)的值匹配,因此代码不会替换这些值,例如“faID”有一个值2090,它也在“uID”中。因此,代码不会替换该值并保留uID(这是一个数字,而不是该用户的值)。@user3841811是否更新了数据集和预期结果?我认为代码做得很好。问题是,我的计算机没有为所有用户(uID)计算用户的值是的,第二个代码正在做我的工作,第一个代码只是确认中心性values@user3841811如果不是代码问题,你想让我怎么做?
library(data.table)
# coerce to data.table and right join on uID
result <- setDT(DF2)[setDT(DF1), on = "uID"][
# replace uID by user_cent_w where available, remove column
!is.na(user_cent_w), uID := user_cent_w][, -"user_cent_w"]
result
uID faID
1: 20909 1
2: 6661 1
3: 15844 1
4: 28065 1
5: 466 1
6: 3113 1
7: 1514 1
8: 3825 1
9: 134766 2
10: 271168 2
11: 16710 2
12: 4071608 2
13: 2046526 2
14: 5081272 2
setDT(DF1)[setDT(DF2), on = "uID", uID := ifelse(is.na(user_cent_w), uID, user_cent_w)]
DF1
faID uID
1: 1 20909
2: 1 6661
3: 1 15844
4: 1 28065
5: 1 466
6: 1 3113
7: 1 1514
8: 1 3825
9: 2 134766
10: 2 271168
11: 2 16710
12: 2 4071608
13: 2 2046526
14: 2 5081272
DF1 <- structure(list(faID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L), uID = c(20909L, 6661L, 1591L, 28065L, 42783L,
3113L, 21647L, 3825L, 134766L, 271168L, 16710L, 4071608L, 2046526L,
5081272L)), .Names = c("faID", "uID"), row.names = c(NA, -14L
), class = "data.frame")
DF2 <- structure(list(uID = c(1591L, 42783L, 21647L, 29695L, 94120L,
83098L, 138776L, 90352L, 115384L, 74483L), user_cent_w = c(15844L,
466L, 1514L, 13958L, 3615L, 128L, 709L, 991L, 8039L, 128L)), .Names = c("uID",
"user_cent_w"), row.names = c(NA, -10L), class = "data.frame")