LoginSignup
2
2

More than 5 years have passed since last update.

dplyr::selectで文字ベクトルの列を操作しようとしてヘマしたので反省文を書く

Last updated at Posted at 2015-11-05

まったく個人的なメモ

アンケート集計ファイルの「自由記述」テキスト列に、特定のキーワードを含むレコードだけ抽出するという単純な作業。
dplyr と strintr を使って何気に操作したら想定外の結果がかえってきて、しばらくして自分の勘違いに気が付いた。

> # 単純な文字列ベクトルを要素とするデータフレーム
> x <- c("ABC","CDE","EFG")
> xx <- data.frame(X = x, stringsAsFactors = FALSE)
> # X列の文字列にCを含むレコードだけみたい
> xx %>% select (X) %>% str_subset("C")
[1] "c(\"ABC\", \"CDE\", \"EFG\")"
> # あれ?
> xx %>% select (X) %>% grep(pattern="C", x = ., value = TRUE)
                             X 
"c(\"ABC\", \"CDE\", \"EFG\")" 
> # うん?
> xx %>% select (X) %>% nchar
 X 
22 
> # dplyr::selectが問題なの? 
> xx $ X %>% str_subset("C")
[1] "ABC" "CDE"
> xx $ X %>%  grep(pattern="C", x = ., value = TRUE)
[1] "ABC" "CDE"
> xx $ X %>% nchar 
[1] 3 3 3
> # どうなってんの?
> xx %>% select (X) %>% dput
structure(list(X = c("ABC", "CDE", "EFG")), row.names = c(NA, 
-3L), class = "data.frame", .Names = "X")
> xx $ X %>% dput
c("ABC", "CDE", "EFG")
> # ああ、そうですか
> ## 結局、こうすれば良いんか
> xx %>% filter (str_detect(X, "C"))
    X
1 ABC
2 CDE
> ## 後でdplyrのソース読め、俺

以上、お粗末さまでした。反省します。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2