【发布时间】:2018-10-25 09:30:27
【问题描述】:
我有两个数据集:
loc <- c("a","b","c","d","e")
id1 <- c(NA,9,3,4,5)
id2 <- c(2,3,7,5,6)
id3 <- c(2,NA,5,NA,7)
cost1 <- c(10,20,30,40,50)
cost2 <- c(50,20,30,30,50)
cost3 <- c(40,20,30,10,20)
dt <- data.frame(loc,id1,id2,id3,cost1,cost2,cost3)
id <- c(1,2,3,4,5,6,7)
rate <- c(0.9,0.8,0.7,0.6,0.5,0.4,0.3)
lookupd_tb <- data.frame(id,rate)
我想做的是将 dt 中的值与 id1、id2 和 id3 的 lookup_tb 进行匹配,如果匹配,则将该 id 的比率乘以其相关成本。
这是我的方法:
dt <- dt %>%
left_join(lookupd_tb , by=c("id1"="id")) %>%
dplyr :: mutate(cost1 = ifelse(!is.na(rate), cost1*rate, cost1)) %>%
dplyr :: select (-rate)
我现在在做什么,工作正常,但我必须为每个变量重复 3 次,我想知道是否有更有效的方法来做到这一点(可能使用 apply 系列?)
我尝试在我的查找表中加入所有三个带有 id 的变量,但是当我的 dt 加入 rate 时,所有成本(cost1、cost2 和 cost3)都将乘以我不想要的相同速率。
感谢您的帮助!
【问题讨论】: