在 R 中提取反斜杠前的文本

Extract text before backslash in R

在 R 中,我有包含此文本列的代码:

在播放器栏中,我只需要反斜杠前的文字。

期望输出

乔伊·沃托

胡安·索托

查理·布莱克蒙

弗雷迪弗里曼

这里是输出结果

structure(list(Player = c("Joey Votto\vottojo01", "Juan Soto\sotoju01", 
"Charlie Blackmon\blackch02", "Freddie Freeman\freemfr01"), 
    TOB = c(321, 304, 288, 274), TB = c(323, 268, 387, 312), 
    G = c(162, 151, 159, 162), WAR = c(8.1, 7.1, 5.5, 5.5)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -4L))

我更喜欢在 R 中使用 dplyr 的代码。

我试图让它与这段代码一起工作,但没有成功:

mutate(Name = str_extract(Player, "(?=\)"))

我查看了 Stackover 建议的解决方案,但没有找到适合我情况的解决方案。如果有遗漏的,请告诉我。

我们可以使用str_remove来匹配\并删除其余的

library(stringr)
 str_remove(str1, "\\.*")
[1] "Charlie Blackmon" "Freddie Freeman" 

如果我们使用 tidyverse 语法

library(dplyr)
df1 <- df1 %>%
    mutate(Player = str_remove(Player, "\\.*"))

-输出

df1
# A tibble: 4 × 5
  Player             TOB    TB     G   WAR
  <chr>            <dbl> <dbl> <dbl> <dbl>
1 Joey Votto         321   323   162   8.1
2 Juan Soto          304   268   151   7.1
3 Charlie Blackmon   288   387   159   5.5
4 Freddie Freeman    274   312   162   5.5

或使用 base Rtrimws

 trimws(df1$Player, whitespace = "\\.*")
[1] "Joey Votto"       "Juan Soto"        "Charlie Blackmon" "Freddie Freeman" 

数据

str1 <- c("Charlie Blackmon\blackch02", "Freddie Freeman\freemfr01")

另一种可能的解决方案,基于stringr::str_extract

library(tidyverse)

df <- structure(list(Player = c("Joey Votto\vottojo01", "Juan Soto\sotoju01", 
"Charlie Blackmon\blackch02", "Freddie Freeman\freemfr01"), 
    TOB = c(321, 304, 288, 274), TB = c(323, 268, 387, 312), 
    G = c(162, 151, 159, 162), WAR = c(8.1, 7.1, 5.5, 5.5)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -4L))

df %>% 
  mutate(Player = str_extract(Player, "^.*(?=\\)"))

#> # A tibble: 4 × 5
#>   Player             TOB    TB     G   WAR
#>   <chr>            <dbl> <dbl> <dbl> <dbl>
#> 1 Joey Votto         321   323   162   8.1
#> 2 Juan Soto          304   268   151   7.1
#> 3 Charlie Blackmon   288   387   159   5.5
#> 4 Freddie Freeman    274   312   162   5.5

从 R 4.0.0 开始,您可以使用原始字符串,因此不需要双反斜杠,只需使用以下语法:r"(your_raw_expression)"(包括括号)。我们可以这样做:

str_remove(df$Player, r"(\.*)")
# [1] "Joey Votto"       "Juan Soto"        "Charlie Blackmon" "Freddie Freeman"

str_extract(df$Player, r"(^.*(?=\))")
# [1] "Joey Votto"       "Juan Soto"        "Charlie Blackmon" "Freddie Freeman"