SAS中是否存在类似Excel Xlookup的函数可实现站点ID匹配站名?
SAS实现双站点名称匹配方案
方法1:PROC SQL 左连接(逻辑和XLOOKUP高度一致,易理解)
这种方法不需要提前对数据集排序,两次关联站点表即可分别匹配出发、到达站点的名称,代码逻辑直观:
proc sql; create table Trips_with_StationNames as select a.*, b.station_name as from_station_name, c.station_name as to_station_name from DivvyTrips a left join DivvyStations b on a.from_station_id = b.station_id left join DivvyStations c on a.to_station_id = c.station_id; quit;
没有匹配到的站点名称会自动留空,和Excel XLOOKUP的缺省值逻辑完全一致。
方法2:DATA步HASH表(大数据量场景效率更高)
如果Trips表数据量较大,用内存哈希表查找的效率会远高于SQL关联,同样不需要提前排序,SAS University Edition完全支持该语法:
data Trips_with_StationNames; set DivvyTrips; /* 首次执行时将站点映射表加载到内存哈希表 */ if _n_ = 1 then do; declare hash h(dataset: 'DivvyStations'); h.defineKey('station_id'); h.defineData('station_name'); h.defineDone(); call missing(station_id, station_name); end; /* 匹配出发站点名称 */ if h.find(key: from_station_id) = 0 then from_station_name = station_name; else from_station_name = ''; /* 匹配到达站点名称 */ if h.find(key: to_station_id) = 0 then to_station_name = station_name; else to_station_name = ''; drop station_id station_name; run;
你判断普通排序后merge无法满足需求是正确的,常规merge只能按单个键值匹配,无法同时处理出发、到达两个不同的匹配键,以上两种方案都可以完美解决需求。
内容的提问来源于stack exchange,提问作者Cami Dastrup
相关产品推荐
相关产品推荐

