【问题标题】:Change position of words within a column更改列中单词的位置
【发布时间】:2019-11-12 20:26:20
【问题描述】:

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

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

[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"

【问题讨论】:

  • 作为初学者:help("gsub")gsub("^(Landkreis) (.+)$", "\\2, \\1", "Landkreis Nordsachsen")

标签: r merge gsub stringr


【解决方案1】:

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

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

myvec <- sapply(vector_of_strings, myfunc)

如果你采用另一种方式,你可以用逗号分隔,以防名称中包含额外的空格:

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))

【讨论】:

    【解决方案2】:

    由于您有一个通用的、固定长度的前缀,您可以使用 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
    

    【讨论】:

      猜你喜欢
      • 2012-10-15
      • 2016-12-11
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2015-06-12
      相关资源
      最近更新 更多