r仅将某些表值替换为备用表中的值 [英] r Replace only some table values with values from alternate table

查看:94
本文介绍了r仅将某些表值替换为备用表中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个"vlookup-and-fill-down"问题.

This is not a "vlookup-and-fill-down" question.

我的源数据非常擅长提供所需的所有数据,只是不是可用形式.音量的最新变化意味着手动调整的修复不再可行.

My source data is excellent at delivering all the data I need, just not in in a usable form. Recent changes in volume mean manually adjusted fixes are no longer feasible.

我有一个库存表和一个服务表.库存报告不包含服务或非库存项目的采购订单数据.服务表(自然地)可以.它们当然是不同的形状.

I have an inventory table and a services table. The inventory report does not contain purchase order data for services or non-inventory items. The services table (naturally) does. They are of course different shapes.

伪编码可能会影响for every inventory$Item in services$Item, replace inventory$onPO with services$onPO.

样本数据

inv <- structure(list(Item = c("10100200", "10100201", "10100202", "10100203", 
"10100204", "10100205-A", "10100206", "10100207", "10100208", 
"10100209", "10100210"), onHand = c(600L, NA, 39L, 0L, NA, NA, 
40L, 0L, 0L, 0L, 0L), demand = c(3300L, NA, 40L, 40L, NA, NA, 
70L, 126L, 10L, 10L, 250L), onPO = c(2700L, NA, 1L, 40L, NA, 
NA, 30L, 126L, 10L, 10L, 250L)), .Names = c("Item", "onHand", 
"demand", "onPO"), row.names = c(NA, -11L), class = c("data.table", 
"data.frame"))

svc <- structure(list(Item = c("10100201", "10100204", "10100205-A"), 
    `Rcv'd` = c(0L, 0L, 44L), Backordered = c(20L, 100L, 18L)), .Names = c("Item", 
"Rcv'd", "Backordered"), row.names = c(NA, -3L), class = c("data.table", 
"data.frame"))

推荐答案

假定您要用Backordered中的值替换onPO中的NA,这是使用dplyr::left_join的解决方案:

Assuming you want to replace NAs in onPO with values from Backordered here is a solution using dplyr::left_join:

library(dplyr);
left_join(inv, svc) %>%
    mutate(onPO = ifelse(is.na(onPO), Backordered, onPO)) %>%
    select(-Backordered, -`Rcv'd`);
#         Item onHand demand onPO
#1    10100200    600   3300 2700
#2    10100201     NA     NA   20
#3    10100202     39     40    1
#4    10100203      0     40   40
#5    10100204     NA     NA  100
#6  10100205-A     NA     NA   18
#7    10100206     40     70   30
#8    10100207      0    126  126
#9    10100208      0     10   10
#10   10100209      0     10   10
#11   10100210      0    250  250

或使用merge在base R中的解决方案:

Or a solution in base R using merge:

inv$onPO <- with(merge(inv, svc, all.x = TRUE), ifelse(is.na(onPO), Backordered, onPO))


或使用coalesce而不是ifelse(由于@thelatemail):


Or using coalesce instead of ifelse (thanks to @thelatemail):

library(dplyr);
left_join(inv, svc) %>%
    mutate(onPO = coalesce(onPO, Backordered)) %>%
    select(-Backordered, -`Rcv'd`);

这篇关于r仅将某些表值替换为备用表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆