R言語でキーワードを含む行を抽出する方法は?

R言語では、grepl()関数を使用してキーワードを含む行をフィルタリングできます。grepl()関数は論理ベクトルを返します。このベクトルは、指定されたキーワードを含む行を示します。

以下に例をあげて、grepl() 関数を使用して、キーワードを含む行を抽出する方法を紹介します:

# 创建一个包含文本的数据框
data <- data.frame(
  id = c(1, 2, 3, 4, 5),
  text = c("This is a sample text.",
           "Another text example.",
           "Some more random text.",
           "Just some words.",
           "Text text text.")
)

# 筛选出包含关键词"text"的行
filtered_data <- data[grepl("text", data$text, ignore.case = TRUE), ]

# 输出筛选结果
print(filtered_data)

上記のコードを実行すると、キーワード「text」を含む行が出力されます。

  id                  text
1  1 This is a sample text.
2  2  Another text example.
3  3 Some more random text.
5  5      Text text text.

grepl 関数では、1 つ目の引数が検索したいキーワード、2 つ目が検索対象のテキストです。ignore.case = TRUE とすると大文字小文字を無視します。上記の例では ignore.case = TRUE としているので、キーワードの大文字小文字を無視しています。キーワードの大文字小文字を厳密に一致させたい場合は、ignore.case 引数を FALSE にします。

bannerAds