tidyr 的 extract

R 中級 Regular Expressions

Angelo Zehr

Data Journalist

目前用到的函式

  • str_match
  • str_replace
  • str_match_all
  • str_replace_all
  • ...
R 中級 Regular Expressions

規則表示式與資料框交會點:

extract(
    data,
    col,
    into,
    regex = "([[:alnum:]]+)",
    remove = TRUE,
    convert = FALSE,
    ...
 )
R 中級 Regular Expressions

extract 的引數

extract(
    data,
    col,
    into,
    regex = "([[:alnum:]]+)",
    remove = TRUE,
    convert = FALSE,
    ...
 )
  • data

  • col

  • into

  • regex

  • remove

  • convert

R 中級 Regular Expressions

Movies 資料框

R 中級 Regular Expressions

str_match 能做到的事

screenshot of a table

screens_per_movie %<>%
  mutate(
    is_3d = str_match(line, "3D")
  )
R 中級 Regular Expressions

str_match 的結果長怎樣

screenshot of a table

screens_per_movie %<>%
  mutate(
    is_3d = str_match(line, "3D")
  )
R 中級 Regular Expressions

str_match 只能擷取一項資訊

screenshot of a table

R 中級 Regular Expressions

extract 能幫上的忙

R 中級 Regular Expressions

extract 能幫上的忙

screenshot of a table

extract(
  screens_per_movie,
  col = "line",
  into = c("is_3d", "screens"),
  regex = "(3D).*?(\\d+)$",
  remove = FALSE
 )
R 中級 Regular Expressions

extract 的結果

screenshot of a table

extract(
  screens_per_movie,
  col = "line",
  into = c("is_3d", "screens"),
  regex = "(3D).*?(\\d+)$",
  remove = FALSE
)
R 中級 Regular Expressions

一起來練習吧!

R 中級 Regular Expressions

Preparing Video For Download...