问题描述
|
Windows 7上的R版本2.11.1 32位
我有两个数据集,如下所示:
data_set_A:
USER_B ACTION
10 0.1
11 0.3
12 0.1
data_set_B:
USER_A USER_B ACTION
1 10 0.2
1 11 0.1
1 15 0.1
2 12 0.2
怎么把USER_B
中的ACTION
从data_set_A
增加到data_set_B
? data_set_A
中的USER_B
是data_set_B
中USER_B
的子集。
对于上面的示例,可能是:
USER_A USER_B ACTION
1 10 0.2+0.1
1 11 0.1+0.3
1 15 0.1
2 12 0.2+0.1
在ѭ5中,我不需要考虑USER_A
,只需考虑the3中出现的data_set_A
。
我想知道如果不一一完成就能实现吗?
解决方法
dfa <- data.frame(
user_b = 10:12,action = c(0.1,0.3,0.1)
)
dfb <- data.frame(
user_a = c(1,1,2),user_b = c(10,11,15,12),action = c(0.2,0.1,0.2)
)
action <- dfa$action[match(dfb$user_b,dfa$user_b)]
action[is.na(action)] <- 0
dfb$action <- dfb$action + action
dfb
user_a user_b action
1 1 10 0.3
2 1 11 0.4
3 1 15 0.1
4 2 12 0.3
,一种方法是等效地对两个数据集进行数据库合并,以形成所需的操作对,然后对它们进行求和。使用@Andrie \的示例代码:
dfa <- data.frame(
user_b = 10:12,0.2)
)
解决方案代码
我将首先介绍完整的解决方案,然后说明步骤:
mdat <- merge(dfb,dfa,by = \"user_b\",all.x = TRUE)
res <- data.frame(mdat[,c(2,1)],action = rowSums(mdat[,c(\"action.x\",\"action.y\")],na.rm = TRUE))
res <- res[order(res$user_a,res$user_b),]
res
现在包含结果。
说明
我们首先合并两个数据帧,在ѭ19上匹配:
## merge the data
mdat <- merge(dfb,all.x = TRUE)
mdat
给予:
> mdat
user_b user_a action.x action.y
1 10 1 0.2 0.1
2 11 1 0.1 0.3
3 12 2 0.2 0.1
4 15 1 0.1 NA
然后,我们仅使用此对象创建结果数据帧,并将两行的action.
列求和:
## format the merged data with summed `action`
res <- data.frame(mdat[,na.rm = TRUE))
## reorder
res <- res[order(res$user_a,]
res
导致
> res
user_a user_b action
1 1 10 0.3
2 1 11 0.4
4 1 15 0.1
3 2 12 0.3