我有一些这种格式的数据:
Name Number 1 The Beatles 100 2 Rolling Stones, The 100 3 Puff The Magic Dragon 100 4 The Offspring 100
df <- data.frame(stringsAsFactors=FALSE,
Name = c("The Beatles", "Rolling Stones, The", "Puff The Magic Dragon",
"The Offspring"),
Number = c(100L, 100L, 100L, 100L)
)
我要删除:
但是我想离开:
这是我尝试过的方法,但是它将“ The”从“ Puff the Magic Dragon”中删除,这不是我想要的。
library(stringr)
df$Name <- str_replace(string = df$Name, "\\, The", "")
df$Name <- str_replace(string = df$Name, "The", "")
为此:
Name Number 1 Beatles 100 2 Rolling Stones 100 3 Puff Magic Dragon 100 4 Offspring 100
我想要的输出是:
Name Number 1 Beatles 100 2 Rolling Stones 100 3 Puff The Magic Dragon 100 4 Offspring 100
答案 0 :(得分:3)
您可以使用锚点^
和$
来指示每个字符串的开头和结尾。您还可以将模式组与|
组合在一起以仅使用一个模式,并且可以对str_remove()
使用便捷功能str_replace(replacement = "")
。这些是正则表达式,它们提供了一种非常简洁的字符串操作方法。有关锚点的更多信息,请参见here。
library(tidyverse)
df <- data.frame(
stringsAsFactors = FALSE,
Name = c(
"The Beatles", "Rolling Stones, The", "Puff The Magic Dragon",
"The Offspring"
),
Number = c(100L, 100L, 100L, 100L)
)
df %>%
mutate(Name = str_remove_all(Name, "(^The )|(, The$)"))
#> Name Number
#> 1 Beatles 100
#> 2 Rolling Stones 100
#> 3 Puff The Magic Dragon 100
#> 4 Offspring 100
由reprex package(v0.2.1)于2019-03-14创建
答案 1 :(得分:2)
或与sub
sub("^The |, The$", "", df$Name)
#[1] "Beatles" "Rolling Stones" "Puff The Magic Dragon" "Offspring"
或与str_replace
library(tidyverse)
df %>%
mutate(Name = str_replace(Name, "^The |, The$", ""))
# Name Number
#1 Beatles 100
#2 Rolling Stones 100
#3 Puff The Magic Dragon 100
#4 Offspring 100