使用 str_detect 提取字符串的值

Extracting values of a string with str_detect

我目前有一个具有以下结构的 data.frame (X):

Number Observation
1   34
2   Example
3   Example34% 
4   Example
5   34

我想要的输出是 2 个数据框,一个只包含双重观察值(即 34),另一个包含所有其他内容(字符和带有数字和 % 的字符)。

我已经能够使用以下方法获得数量观察值:

y <- x[str_detect(x$Observation,("([0-9])")),]

但它也包括对字符和数字的观察。当我否定它时 !str_detect(...) 我只得到一个字符输出而忽略了 Example34%。有没有办法 str_detect 只有 数值然后 !that 获得其他一切?

所需输出示例:

在正则表达式

的开始 ^ 和结束 $ 中使用锚点
library(tidyverse)

data_example <- tibble::tribble(
  ~Number, ~Observation,
  1L, "34",
  2L, "Example",
  3L, "Example34%",
  4L, "Example",
  5L, "34"
)

tidy_solution <- data_example %>%
  mutate(
    just_numbers = Observation %>% str_extract("^[:digit:]+$"),
    just_not_numbers = if_else(just_numbers %>% is.na(), Observation, NA_character_),
    full_ans = coalesce(just_numbers, just_not_numbers)
  )

tidy_solution
#> # A tibble: 5 x 5
#>   Number Observation just_numbers just_not_numbers full_ans  
#>    <int> <chr>       <chr>        <chr>            <chr>     
#> 1      1 34          34           <NA>             34        
#> 2      2 Example     <NA>         Example          Example   
#> 3      3 Example34%  <NA>         Example34%       Example34%
#> 4      4 Example     <NA>         Example          Example   
#> 5      5 34          34           <NA>             34

a <- tidy_solution %>%
  select(Number, just_numbers) %>%
  na.omit()

a
#> # A tibble: 2 x 2
#>   Number just_numbers
#>    <int> <chr>       
#> 1      1 34          
#> 2      5 34


b <- tidy_solution %>%
  select(Number, just_not_numbers) %>%
  na.omit()

reprex package (v0.3.0)

于 2020 年 6 月 10 日创建

一种方法是找到一个输出并使用 anti_join 得到另一个。

library(dplyr)
library(stringr)

df1 <- df %>% filter(str_detect(Observation, '[A-Za-z]'))
df2 <- anti_join(df, df1)

df1
#  Number Observation
#1      2     Example
#2      3  Example34%
#3      4     Example

df2
#  Number Observation
#1      1          34
#2      5          34

df1 中,我们包括具有任何字母的行,而 df2 是其他所有内容。

数据

df <- structure(list(Number = 1:5, Observation = c("34", "Example", 
"Example34%", "Example", "34")), class = "data.frame", row.names=c(NA, -5L))