我的数据集中有一个名为“ Market.Pair”的列,其中包含有关某些航班的出发地和目的地的信息。例如:
input <- data.frame(Market.Pair = c("US to/from CA", "HOU to/from DFW/DAL", "EWR/JFK to/from LAX/SFO", "US-NYC to/from FR-PAR", "US to/from Asia"))
input
所有两个字母代表国家(例如,美国,加拿大)。所有三个字母词(或由“ /”分隔的多个三个字母词)代表机场(例如,HOU,DFW / DAL)。XX-XXX形式的所有单词都代表城市(例如US-NYC)。换句话说,代表区域,例如亚洲或欧洲。
我想将此列拆分为多个列:
output<- data.frame(Air.1 = c("HOU", "EWR/JFK", "", "", ""), Air.2 = c("DFW/DAL", "LAX/SFO", "", "", ""), City.1 = c("","","US-NYC", "", ""), City.2 = c("","","FR-PAR", "", ""), Country.1 = c("","","","US", "US"), Coutry.2 = c("","","","CA", ""), Region.1 = c("","","", "", "Asia"), Region.2 = c("","","", "", ""))
output
我是regex的新手,所以我们将不胜感激!
input <- data.frame(Market.Pair = c("US to/from CA", "HOU to/from DFW/DAL",
"EWR/JFK to/from LAX/SFO", "US-NYC to/from FR-PAR",
"US to EMEA/India"))
sp <- strsplit(as.character(input$Market.Pair), '\\s+to(/from)?\\s+')
f <- Vectorize(function(x)
if (grepl('\\-', x)) 'City' else if (nchar(x) == 2) 'Country' else
if (grepl('^[A-Z]+/[A-Z]+$|^[A-Z]+$', x)) 'Air' else 'Region')
dd <- lapply(sp, function(x) {
## set up output matrix
cn <- sort(levels(interaction(c('Air','City','Country','Region'), 1:2)))
m <- matrix('', 1, length(cn), dimnames = list(NULL, cn))
## use f above and add the suffix
xx <- f(x)
nn <- setNames(x, paste(xx, ave(xx, xx, FUN = seq_along), sep = '.'))
## match
m[, names(nn)] <- nn
m
})
do.call('rbind.data.frame', dd)
# Air.1 Air.2 City.1 City.2 Country.1 Country.2 Region.1 Region.2
# 1 US CA
# 2 HOU DFW/DAL
# 3 EWR/JFK LAX/SFO
# 4 US-NYC FR-PAR
# 5 US EMEA/India
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句