试图提取 R 列中的特定字符?

Trying to extract specific characters in a column in R?

列中的内容显示如下 $1,521+ 2 bds。我想提取 1521 并将其放入新列中。我知道这可以在 alteryx 中使用正则表达式完成,我可以做 R 吗?

例如:

library(tidyverse)    

#generate some data
tbl <- tibble(string = str_c('$', as.character(seq(1521, 1541, 1)), '+', ' 2bds'))

new_col <- 
    tbl$string %>%
    str_split('\+',simplify = TRUE) %>% 
    `[`(, 1) %>% 
    str_sub(2, -1) #get rid of '$' at the start

mutate(tbl, number = new_col)
#> # A tibble: 21 x 2
#>    string      number
#>    <chr>       <chr> 
#>  1 21+ 2bds 1521  
#>  2 22+ 2bds 1522  
#>  3 23+ 2bds 1523  
#>  4 24+ 2bds 1524  
#>  5 25+ 2bds 1525  
#>  6 26+ 2bds 1526  
#>  7 27+ 2bds 1527  
#>  8 28+ 2bds 1528  
#>  9 29+ 2bds 1529  
#> 10 30+ 2bds 1530  
#> # … with 11 more rows

reprex package (v2.0.0)

创建于 2021-06-12

下面的怎么样?:

library(tidyverse)

x <- ',521+ 2 bds'

parse_number(x)

我们可以使用 sub 来自 base R

as.numeric( sub("\$(\d+),(\d+).*", "\1\2", x))
#[1] 1521

数据

x <- ',521+ 2 bds'