首页 > 解决方案 > 数据框 1 中的参考坐标列填充数据框 2 中的起点和目标坐标

问题描述

数据框 1(aircode)有一个名为 Coordinates 和 Ident 的列。(参考数据框)数据框 2(数据)有一个称为 Origin 的列和一个称为 Destination 的列。(主数据框)

我想在数据框 2 中再添加 2 列,称为 Origin_coordinates 和 Destination_coordinates。

Ident 包含机场 IATA 代码,Origin 和 Destination 也是如此。我正在考虑使用某种 Vlookup 函数,以便它们可以相互引用。然后我可以为起点和终点提取适当的机场坐标并将它们应用于新列

我只知道如何合并数据框,但这并不能满足我的要求。

Merged=merge(data, aircode, by.x="Origin", by.y="ident", all.x = TRUE)

如果您想要实际文件,请查看此处(ABIA.csv) 的数据框 2 和此处的 (airport-codes) 数据框 1

标签: r

解决方案


下面是一个使用data.table包的例子:

library(data.table)

# read data
data <- fread("https://raw.githubusercontent.com/RehanDaya/STA380/master/data/ABIA.csv")
aircode <- fread("https://datahub.io/core/airport-codes/r/airport-codes.csv")

# get unique values for "vlookup"
d <- unique(data[, .(Origin, Dest)])
ac <- unique(aircode[, .(ident, name)])

# Function to map values
find_name <- function(orig, dest) {
    .orig <- ac[ident %like% orig]$name[1]
    .dest <- ac[ident %like% dest]$name[1]
    return(list(Origin.Name = .orig, Dest.Name = .dest))
}

# Create two new columns for name
d[, c("Origin.Name", "Dest.Name") := find_name(Origin, Dest), by = .I]

# print result
head(d, 5)
#    Origin Dest                     Origin.Name                                Dest.Name
# 1:    MEM  AUS   Memphis International Airport          Austin Robert Mueller Municipal
# 2:    AUS  ORD Austin Robert Mueller Municipal     Chicago O'Hare International Airport
# 3:    AUS  PHX Austin Robert Mueller Municipal Phoenix Sky Harbor International Airport
# 4:    AUS  MEM Austin Robert Mueller Municipal            Memphis International Airport
# 5:    AUS  DFW Austin Robert Mueller Municipal         Würzburg-Schenkenturm Airport

这也可以通过引用更新 data.table 来完成,而无需定义单独的函数(如我之前示例中的 find_name 函数):

library(data.table)

# read data
data <- fread("https://raw.githubusercontent.com/RehanDaya/STA380/master/data/ABIA.csv")
aircode <- fread("https://datahub.io/core/airport-codes/r/airport-codes.csv")

# get unique values for "vlookup"
d <- unique(data[, .(Origin, Dest)])
ac <- unique(aircode[, .(ident, name)])

# Create two new columns for name
d[, `:=` (
    Origin.Name = ac[ident %like% Origin]$name[1], 
    Dest.Name = ac[ident %like% Dest]$name[1]
  ), 
  by = .(Origin, Dest)]

# print result
head(d, 5)
#    Origin Dest                     Origin.Name                                Dest.Name
# 1:    MEM  AUS   Memphis International Airport          Austin Robert Mueller Municipal
# 2:    AUS  ORD Austin Robert Mueller Municipal     Chicago O'Hare International Airport
# 3:    AUS  PHX Austin Robert Mueller Municipal Phoenix Sky Harbor International Airport
# 4:    AUS  MEM Austin Robert Mueller Municipal            Memphis International Airport
# 5:    AUS  DFW Austin Robert Mueller Municipal         Würzburg-Schenkenturm Airport

推荐阅读