0
0

More than 5 years have passed since last update.

if 条件とクラスタ名を同じにしたいとき #rstatsj

Last updated at Posted at 2013-11-06

例えば、ユーザIDとユーザの特性値 X のデータがあったとします。

データ作成
id <- 1:10
x <- runif(length(id))
data <- data.frame(UserID=id, X=x)
print(data)
結果
   UserID         X
1       1 0.9502438
2       2 0.3470344
3       3 0.4456312
4       4 0.1642439
5       5 0.3765186
6       6 0.4722742
7       7 0.3034376
8       8 0.7143706
9       9 0.5404237
10     10 0.5648573

このユーザの特性値 X を使って、ユーザを下記の3つのクラスタに分けたいとします。

  • 0.4未満
  • 0.4 ~ 0.6
  • 0.6以上

そのとき、if 条件式とクラスタ名を同じにしたい時があります。
しかし、次のように書くと、なんだか同じことを何度も書いているような気がして冗長な感じがします。

改善前
result <- transform(data, 
                    Cluster=ifelse(x < 0.4, "x < 0.4", 
                            ifelse(0.4 <= x & x < 0.6, "0.4 <= x & x < 0.6",
                                                       "0.6 <= x")))

そんなときは、次のように書いてはいかがでしょうか。

改善後
exp1 <- expression(x < 0.4)
exp2 <- expression(0.4 <= x & x < 0.6)
exp3 <- expression(0.6 <= x)
result <- transform(data, 
                    Cluster=ifelse(eval(exp1), as.character(exp1), 
                            ifelse(eval(exp2), as.character(exp2),
                                               as.character(exp3))))
print(result)

expression を別にすることで、すっきりしたような気がします。
お試しあれ。

結果
   UserID         X            Cluster
1       1 0.9502438           0.6 <= x
2       2 0.3470344            x < 0.4
3       3 0.4456312 0.4 <= x & x < 0.6
4       4 0.1642439            x < 0.4
5       5 0.3765186            x < 0.4
6       6 0.4722742 0.4 <= x & x < 0.6
7       7 0.3034376            x < 0.4
8       8 0.7143706           0.6 <= x
9       9 0.5404237 0.4 <= x & x < 0.6
10     10 0.5648573 0.4 <= x & x < 0.6
0
0
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
0
0