【问题标题】:Need to extract individual characters from a string column using R需要使用 R 从字符串列中提取单个字符
【发布时间】:2023-03-16 05:41:01
【问题描述】:

背景

下面是我的 gamedata 数据集,以 dput 形式呈现——它包含一些 MLB 比赛的线得分。

structure(list(team = c("NYM", "NYM", "BOS", "NYM", "BOS"), linescore = c("010000000", 
"(10)1140006x", "002200010", "00000(11)01x", "311200"), ondate = structure(c(18475, 
18476, 18487, 18489, 18494), class = "Date")), class = "data.frame", row.names = c(NA, 
-5L))

例如,这里是一个行分数:“002200010”。

有些行分数以“x”结尾,有些在括号中包含两位数,如“00000(11)01x”。括号中没有的每个数字表示球队在该局中得分的次数。如果一支球队在一局中得分超过 9 分,则数字放在括号中,因此在行得分“00000(11)01x”中,该队在第六局得分 11 分,并且没有在底部击球第九个(用“x”表示)。

并非每个线得分都​​有九局。有些有更多,有些只有六个。

我需要做什么

首先,我需要做的是获取一支球队在每局比赛中得分多少,例如第一局、第二局、第三局等等,然后将每个在新列中得分。我更喜欢使用 dplyr 的解决方案。

我查看了 stackoverflow 的建议解决方案,但没有找到符合我需要的解决方案。如果有的话,如果你能分享它的网址,我将不胜感激。

我已尝试使用此代码:

gamedata %>%
  select(ondate, team, linescore) %>%
  mutate(inng1 = str_extract(linescore, "\\d|\\(\\d{2}\\)"))

这是输出:

ondate      team linescore    inng1
2020-08-01  NYM 010000000       0   
2020-08-02  NYM (10)1140006x  (10)  
2020-08-13  BOS 002200010       0   
2020-08-15  NYM 00000(11)01x    0   
2020-08-20  BOS 311200          3

第二,如何去掉inng1列中'10'的括号?

下面的代码产生了它下面的错误

gamedata %>%
  select(ondate, team, linescore) %>%
  mutate(inng1 = str_extract(linescore, "\\d|\\(\\d{2}\\)"))
 str_remove_all(inng1,"[()]")

这是我收到的错误消息:

“stri_replace_all_regex(string, pattern, fix_replacement(replacement), : object 'inng1' not found”中的错误”

第三,我需要知道如何提取每个附加局的得分,从第二局开始,将每个值放在自己的列中,例如 inng2、inng3 等等。

最后,我应该有上面显示的输出(每个两位数的局都没有括号),每个局都有一列,所以会有一个标题为“inng1”、“inng2”、“inng3”、“ inng4",以此类推。局列中的数据需要是数字,稍后我将对其进行求和。

【问题讨论】:

  • inng1 列包含每个观察值的“linescore”列中的第一个值。 inng2 列包含每个观察值的“linescore”列中的第二个值,依此类推。括号中的数字算作一个值。
  • 你能告诉我任何字符串中的两个右括号是什么意思吗?额外的右括号是否总是后跟x
  • AnilGoyal,如果您指的是第二个观察值中的行得分中的最后一个括号,那是一个错误。 'x' 后面不应该有括号。
  • 是的,我只是指那个。看我的回答。请检查。如果这有效,我会添加适当的解释。
  • 我认为必须删除,因为 OP 已经声明他想要数字输出

标签: r regex string dplyr


【解决方案1】:

这样就可以了-

  • 使用基本 R 的 gsub 进行一些 regex 转换
  • 使用stringr::str_trimstringr::str_count()(虽然这是可选的)
  • 使用tidyr::separate
  • 还有dplyr::mutate

步骤-

  • 从字符串linescore 中删除x(我将其更改为新列,您也可以更改现有列)
  • 在正则表达式的帮助下再次使用 gsub 将括号外的每个字符替换为该字符加上一个空格
  • 此后删除括号字符串
  • 使用tidyr::separate 将字符串分别分成不同的列。
  • 使用convert = TRUE 将每个字符串转换为数字。

对于正则表达式转换解释检查this

library(tidyverse)
df <- structure(list(team = c("NYM", "NYM", "BOS", "NYM", "BOS"), linescore = c("010000000", 
                                                                                "(10)1140006x", "002200010", "00000(11)01x", "311200"), ondate = structure(c(18475, 
                                                                                                                                                             18476, 18487, 18489, 18494), class = "Date")), class = "data.frame", row.names = c(NA, 
                                                                                                                                                                                                                                                -5L))

df %>%
  mutate(inn = gsub('x', '', linescore),
         inn = str_trim(gsub("(.)(?![^(]*\\))", "\\1 ", inn, perl=TRUE)),
         inn = gsub('\\(|\\)', '', inn),
         innings_count = 1 + str_count(inn, ' ')) %>%
  separate(inn, into = paste0('innings_', seq(max(.$innings_count))), sep = ' ', fill = 'right', convert = TRUE)
#>   team    linescore     ondate innings_1 innings_2 innings_3 innings_4
#> 1  NYM    010000000 2020-08-01         0         1         0         0
#> 2  NYM (10)1140006x 2020-08-02        10         1         1         4
#> 3  BOS    002200010 2020-08-13         0         0         2         2
#> 4  NYM 00000(11)01x 2020-08-15         0         0         0         0
#> 5  BOS       311200 2020-08-20         3         1         1         2
#>   innings_5 innings_6 innings_7 innings_8 innings_9 innings_count
#> 1         0         0         0         0         0             9
#> 2         0         0         0         6        NA             8
#> 3         0         0         0         1         0             9
#> 4         0        11         0         1        NA             8
#> 5         0         0        NA        NA        NA             6

【讨论】:

  • 当我运行此代码时,我会在“innings_1”列中获得第二场比赛的整个线得分,而该行的其余部分则填写了 NA。
  • 好家伙。我正在进一步尝试,我怎么能将 (, 1, 0, ) 正则表达式 10
  • @TarJae 使用这个gsub("[(,) ]", "", "(, 1, 0, )")
  • AnilGoyal,当我测试您的代码时,输​​出包含“x”值;然而,在我运行它时产生错误的类型转换代码中,x 都被替换为我更喜欢的 NA。
  • 'innings_count' 应该是 9,8,9,8,6,而不是 9,9,9,9,6。
【解决方案2】:

解决方案02

这是您可以用于此问题的另一种解决方案,它比第一个更有效,主要基于purrr 系列函数:

library(dplyr)
library(purrr)

df %>%
  bind_cols(
    map(df %>% select(linescore), ~ strsplit(.x, "\\(|\\)")) %>%
      flatten() %>%
      map_dfr(~ map(.x, ~ if(nchar(.x) > 2) strsplit(.x, "")[[1]] else .x) %>%
                reduce(~ c(.x, .y)) %>%
                keep(~ nchar(.x) != 0) %>% t() %>%
                as_tibble() %>% 
                set_names(~ paste0("inng", 1:length(.x)))) %>%
      mutate(across(everything(), ~ replace(.x, .x == "x", NA_character_)), 
             count_inng = pmap_dbl(cur_data(), ~ sum(!is.na(c(...)))), 
             sums_inng = pmap_dbl(select(cur_data(), starts_with("inng")), 
                                  ~ sum(as.numeric(c(...)), na.rm = TRUE)))
  )

  team    linescore     ondate inng1 inng2 inng3 inng4 inng5 inng6 inng7 inng8 inng9 count_inng
1  NYM    010000000 2020-08-01     0     1     0     0     0     0     0     0     0          9
2  NYM (10)1140006x 2020-08-02    10     1     1     4     0     0     0     6  <NA>          8
3  BOS    002200010 2020-08-13     0     0     2     2     0     0     0     1     0          9
4  NYM 00000(11)01x 2020-08-15     0     0     0     0     0    11     0     1  <NA>          8
5  BOS       311200 2020-08-20     3     1     1     2     0     0  <NA>  <NA>  <NA>          6
  sums_inng
1         1
2        22
3         5
4        12
5         7

解决方案01

我对我的解决方案进行了一些修改,因为它错误地替换了输出向量中的两位数,我认为它已得到修复。 我认为这个解决方案可能会对您有所帮助。为此,我决定编写一个自定义函数来检测两位数并修剪分数的输出:

library(dplyr)
library(stringr)
library(tidyr)
library(purrr)

fn <- function(x) {
  out <- c()
  if(str_detect(x, "\\((\\d){2}\\)")) {
    double <- str_replace_all(str_extract(x, "\\((\\d){2}\\)"), "[)()]", "")
    ind <- str_locate(x, "\\(")
    x <- str_remove(x, "\\((\\d){2}\\)")
    out <- c(out, str_split(x, "")[[1]])
    out[(ind[1, 1]+1):(length(out)+1)] <- out[(ind[1, 1]):length(out)]
    out[ind] <- double
  } else {
    out <- c(out, str_split(x, "")[[1]])
  }
  if(any(grepl(")", out))) {
    out <- out[-which(out == ")")]
  }
  out
}

# Test
fn("(10)1140006x)")
[1] "10" "1"  "1"  "4"  "0"  "0"  "0"  "6"  "x" 

然后我们以逐行操作将其应用于我们的数据集:

df %>%
  mutate(linescore = map(linescore, fn)) %>% 
  unnest_wider(linescore) %>%
  rename_with(~ gsub("(\\.\\.\\.)(\\d)", paste0("inng", "\\2"), .), starts_with("...")) %>%
  mutate(across(starts_with("inng"), ~ {replace(.x, .x == "x", NA)
    as.numeric(.x)}), 
    inns_count = pmap_dbl(select(cur_data(), starts_with("inng")), 
                          ~ sum(!is.na(c(...)))), 
    inns_sums = pmap_dbl(select(cur_data(), starts_with("inng")), 
                         ~ sum(c(...), na.rm = TRUE)))

# A tibble: 5 x 13
  team  inng1 inng2 inng3 inng4 inng5 inng6 inng7 inng8 inng9 ondate     inns_count inns_sums
  <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <date>          <dbl>     <dbl>
1 NYM       0     1     0     0     0     0     0     0     0 2020-08-01          9         1
2 NYM      10     1     1     4     0     0     0     6    NA 2020-08-02          8        22
3 BOS       0     0     2     2     0     0     0     1     0 2020-08-13          9         5
4 NYM       0     0     0     0     0    11     0     1    NA 2020-08-15          8        12
5 BOS       3     1     1     2     0     0    NA    NA    NA 2020-08-20          6         7

【讨论】:

  • 我需要先对其稍作修改。是的,我会这样做的。
  • 好家伙。我正在进一步尝试,我怎么能将 (, 1, 0, ) 正则表达式 10
  • @TarJae 尝试反向。参考this问题
  • 如果 x 留在任何地方,则值不能是数字。所以必须删除恕我直言
  • Anoushiravan,“x”值仅用于棒球,表示主队在最后一局的下半场没有击球。 “x”出现时,只会出现在乐谱的末尾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 2015-10-16
  • 2021-10-04
  • 1970-01-01
相关资源
最近更新 更多