如何解决数据框1中的“参考坐标”列可填充数据框2中的起点和终点坐标
数据框1(航空代码)有一列称为“坐标和标识”。 (参考数据框) 数据框2(data)具有称为Origin的列和称为Destination的列。 (主数据帧)
我想在数据框2中再添加2列,分别称为Origin_coordinates和Destination_coordinates。
身份包含机场IATA代码,始发地和目的地也是如此。我当时在考虑使用某种Vlookup函数,以便它们可以互相引用。然后,我可以提取适当的出发地和目的地的机场坐标并将其应用于新列
我只知道如何合并数据框,但这并不能满足我的要求。
Merged=merge(data,aircode,by.x="Origin",by.y="ident",all.x = TRUE)
如果您想要实际的文件,请查看数据帧2的here(ABIA.csv)和数据帧1的here(机场代码)
解决方法
下面是使用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[,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。