Help us understand the problem. What is going on with this article?

【R】Rのsubsetで文字列の検索を掛ける方法

More than 5 years have passed since last update.

以下のようなデータフレームがある状態。

a <- data.frame(col1 = c("dog_a","cat_a","cat_b","dog_a","dog_b","cat_a","cat_c"), col2 = c(10,10,20,50,40,20,30), col3 = c(1,2,3,5,1,5,7))
   col1 col2 col3
1 dog_a   10    1
2 cat_a   10    2
3 cat_b   20    3
4 dog_a   50    5
5 dog_b   40    1
6 cat_a   20    5
7 cat_c   30    7

ここで、以下のようにdogという文字列を含んだもののみを抽出したい。

   col1 col2 col3
1 dog_a   10    1
4 dog_a   50    5
5 dog_b   40    1

ここでは、subset()の中でgrepl()を以下のように使う。

a <- subset(a, grepl("dog", a$col1))

grep()は、指定した条件にマッチした列の列番を返す関数。以下の様なイメージ。

grepl("dog", a$col1))  
[1] 1 4 5

一方で、grepl()はTRUEかFALSEを値にもったベクターを返す。

grepl("dog", a$col1)
[1]  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE

subset()では論理値が必要になるので、greplを使って処理する。

参照

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした