r - 数据框 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)
解决方案
下面是一个使用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
推荐阅读
- javascript - Dynamo DB - 更新/删除
- listview - 单击按钮时在列表视图中传递数据
- linux - 使用 csplit 将大文件划分为具有确定名称的小文件
- computer-vision - 计算机视觉
- python - 通过拆分计算列表python中的总数
- java - 如何在标记自定义信息窗口上刷新 ImageView
- javascript - 如何制作客户端指纹javascript
- ios - 通过滑动而不是点击选择的 UITableViewCell
- python - MainWindow 不会同时处理事件和用户操作
- facebook - Facebook Graph APi 不回馈页面本身所写的评论