3

I have data that looks like this:

df <- tribble(
    ~name, ~value,
    "Jake Lake MLP", 10, 
    "Bay May CE", 5,
    "Drake Cake Jr. DSF", 9.1,
    "Sam Ram IR QQQZ", 1
)

I want to trim all the names so that they are:

"Jake Lake",
"Bay May", 
"Drake Cake Jr.",
"Sam Ram IR"

Basically removing everything after the last space.

I tried:

df %>% mutate(name = str_replace(name, "\\s.*$", ""))

But it's not quite what I want!

4

1 回答 1

6

我们可以用sub

df %>% 
    mutate(name = sub("\\s+[^ ]+$", "", name))

或相同的模式str_replace

df %>% 
   mutate(name = str_replace(name, "\\s[^ ]+$", ""))
# A tibble: 4 × 2
#            name value
#           <chr> <dbl>
#1      Jake Lake  10.0
#2        Bay May   5.0
#3 Drake Cake Jr.   9.1
#4     Sam Ram IR   1.0

该模式指示一个空格 ( \\s) 后跟一个或多个非空格(否则它可以\\S+),直到字符串的末尾,并将其替换为空格""。在 OP 的代码中,它是非特定的 ( .*)。

于 2016-10-19T22:43:56.023 回答