4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【R】数値を文字列に置換する

Last updated at Posted at 2017-03-14

今更感はあるが数値を文字列に置換する際にfactor関数を使えば楽にできるのでは?
と思い立ったのでメモ。


require(dplyr)

# データとして10コの1〜4までの乱数を用意
set.seed(71)
x <- floor(runif(n = 10, min = 1, max = (4 + 1)))
data <- tibble(V1 = x)

# 1 : X, 2 : Y, 3 : Z, 4 : Wというように置換する

# 方法1 : ifelseをつかう
data %>% 
  mutate(V2 = ifelse(V1 == 1, 'X', ifelse(V1 == 2, 'Y', ifelse(V1 == 3, 'Z', 'W'))))

# 方法2 : factorを使う
data %>% 
  mutate(V2 = factor(V1, levels = 1:4, labels = c('X', 'Y', 'Z', 'W')))

2値を置き換えるのであればifelseで十分だが、値が3種類以上ならばfactor関数を使ったほうが可読性は高い。
ただfactor関数を使った場合は出力結果が文字列型ではない、タイトル詐欺になってしまった…。

もっとスマートな書き方を教えてもらいました、コメントを参照

4
5
4

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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?