開始使用免費開始

建立符合需求的正規表示式

在這個練習中,你要重現影片練習剛示範的做法,從資料框 screens_per_movie"line" 欄中擷取字母 "3D"

為了讓 extract() 函式正確運作,你需要滿足以下條件:正規表示式 regex 中的擷取群組數量,必須與向量 into 的長度完全相同。否則會發生錯誤。

你能解決這個問題,讓 "3D" 與一個或多個數字 \\d+ 能從資料框 screens_per_movie 中正確擷取出來嗎?

本練習屬於課程

R 中級 Regular Expressions

檢視課程

練習說明

  • 建立一個包含兩個擷取群組 () 的正規表示式 regex。這兩個群組的內容會被擷取到新的欄位中。
  • 確認不要移除原始的文字欄。
  • 確認第二個擷取到的群組會被轉換為數字。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

extract(
  screens_per_movie,
  line,
  into = c("is_3d", "screens"),
  # Capture two groups: "3D" and "one or more digits"
  regex = "___.*?___$",
  # Pass TRUE or FALSE, the original column should not be removed
  remove = ___,
  # Pass TRUE or FALSE, the result should get converted to numbers
  convert = ___
)
編輯並執行程式碼