正则表达式 - 将一列拆分为多个列,R中没有明确的分隔符

时间:2016-03-15 02:04:49

标签: regex r

我的数据集中有一个名为“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的新手,所以任何帮助都会非常感激!

2 个答案:

答案 0 :(得分:4)

这是一种相当手动的方法,但它应该仍然非常有效。它使用我的&#34; splitstackshape&#34;中的cSplit。用于拆分列的包,然后使用&#34; data.table&#34;按条件子集。通过引用创建新值。最后,它使用dcast(再次来自&#34; data.table&#34;)进入宽幅格式。

这里有一些新的示例数据,其中包含您在评论中描述的条件。

input <- data.frame(
  Market.Pair = c(
    "US to/from CA", "HOU to/from DFW/DAL",            # Your sample data
    "EWR/JFK to/from LAX/SFO", 
    "US-NYC to/from FR-PAR", "US to/from Asia", 
    "Latin America/Mexico to EMEA/India",              # Some only "to", exception to "/"
    "EWR to HKG/NRT, JFK to HKG"))                     # Some > 1 pair of values per row

这是一种可能的方法:

library(splitstackshape)
## First, take care of data combined in single rows
x <- cSplit(input, "Market.Pair", ",", "long")

## Add indicator for row names
x[, rn := 1:nrow(x)]

## Split on to/from or to
x <- cSplit(x, "Market.Pair", " to/from | to ", "long", fixed = FALSE, 
            stripWhite = FALSE, type.convert = FALSE)

## Add a column named "type" filled with 'Region' as the value
x[, type := "Region"]

## Using your defined conditions, you can replace the values in the
##   'type' column by reference. Here's 'Air'...
x[nchar(Market.Pair) == 3 | grepl("^.../...$", Market.Pair), type := "Air"]

## ... here's 'Country'
x[nchar(Market.Pair) == 2, type := "Country"]

## ... and here's 'City'
x[grepl("^..-...$", Market.Pair), type := "City"]

## Add an indicator variable...
x[, ind := sequence(.N), by = .(rn, type)]

现在,您可以使用来自&#34; data.table&#34;

dcast将数据重新整形为宽幅。
dcast(x, rn ~ type + ind, value.var = "Market.Pair", fill = "")
#    rn   Air_1   Air_2 City_1 City_2 Country_1 Country_2             Region_1   Region_2
# 1:  1                                      US        CA                                
# 2:  2     HOU DFW/DAL                                                                  
# 3:  3 EWR/JFK LAX/SFO                                                                  
# 4:  4                 US-NYC FR-PAR                                                    
# 5:  5                                      US                           Asia           
# 6:  6                                                   Latin America/Mexico EMEA/India
# 7:  7     EWR HKG/NRT                                                                  
# 8:  8     JFK     HKG                                                                  

答案 1 :(得分:3)

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