始める無料で始める

grepl と grep(2)

You can use the caret, ^, and the dollar sign, $ to match the content located in the start and end of a string, respectively. This could take us one step closer to a correct pattern for matching only the ".edu" email addresses from our list of emails. But there's more that can be added to make the pattern more robust:

  • @, because a valid email must contain an at-sign.
  • .*, which matches any character (.) zero or more times (*). Both the dot and the asterisk are metacharacters. You can use them to match any character between the at-sign and the ".edu" portion of an email address.
  • \\.edu$, to match the ".edu" part of the email at the end of the string. The \\ part escapes the dot: it tells R that you want to use the . as an actual character.

この演習はコースの一部です

中級 R

コースを見る

演習の手順

  • より高度な正規表現を使って grepl() を実行し、論理ベクトルを返しましょう。結果をそのまま出力してください。
  • 同様に grep() を使ってインデックスのベクトルを作成し、結果を変数 hits に格納しましょう。
  • 再び emails[hits] を使って emails ベクトルを部分集合化しましょう。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# The emails vector has already been defined for you
emails <- c("[email protected]", "[email protected]", "[email protected]",
            "invalid.edu", "[email protected]", "[email protected]")

# Use grepl() to match for .edu addresses more robustly


# Use grep() to match for .edu addresses more robustly, save result to hits


# Subset emails using hits
コードを編集して実行