更改列中单词的位置

Change position of words within a column

我想合并两个数据集,但遇到以下问题:

一个数据集中的县按以下模式命名:

[351] "Lindau (Bodensee), Landkreis"                  "Ostallgäu, Landkreis"                         
[353] "Unterallgäu, Landkreis"                        "Donau-Ries, Landkreis"                        

另一个:

 [641] "Landkreis Nienburg/Weser"                      "Landkreis Nordhausen"                         
 [643] "Landkreis Nordsachsen"                         "Landkreis Nordwestmecklenburg"                
 [645] "Landkreis Northeim"                            "Landkreis Nürnberger Land"                    
 [647] "Landkreis Oberallgäu"                          "Landkreis Oberhavel"                          
 [649] "Landkreis Oberspreewald-Lausitz"               "Landkreis Oder-Spree"    

谁能帮我写几行代码,把所有的表达式都变成下面的形状

"Nordsachsen, Landkreis"

将它们全部放在其他格式中可能更容易,因为您可以用逗号很好地划定界限。但是要按要求回答你的问题,假设只有一个 space,这应该可以解决问题:

myfunc <- function(s) {
    el <- strsplit(s, ' ')[[1]]
    return(paste0(el[2], ', ', el[1]))
}

myvec <- sapply(vector_of_strings, myfunc)

如果你走另一条路,你可以用逗号分开,以防名字中有额外的 space:

myfunc <- function(s) {
    el <- strsplit(s, ',')[[1]]
    el <- trimws(el)
    return(paste0(el[2], ' ', el[1]))
}

myvec <- sapply(vector_of_strings, myfunc)

编辑:如果所有条目都以 Landkreis 开头,您可以实现更具体的内容,而不是用正则表达式概括:

s <- "Landkreis Nordhausen"
trimws(gsub('(Landkreis)(.*?$)', '\2, \1', s))

由于您有一个通用的、固定长度的前缀,您可以使用 separate 删除然后 paste0 附加。

将公共前缀转换为公共后缀的 tidyr 解决方案:

    a <- data.frame(x = c('long words', 'long day', 'long time'))

    a %>%
      separate(x, c('A','B'), sep = 5) %>%
      mutate(
        B = paste0(B,', long')
      ) %>%
      select(-A) # to remove