LoginSignup
7
9

More than 5 years have passed since last update.

Rで複数の異なる要素を一括で置換する

Posted at

最近PythonだけでなくRも使うようになり、Pythonで行っていた処理をRでどう書くのか悩んだのでメモしておきます。

目的

僕は、データの前処理で、日本語の要素を英語に変換したいことがよくあります。
数学を'math'と置換するような方法を書きます。

データセット

適当ですが以下のデータセットを利用します。

library(tidyverse)

df <- tibble(
  subject = c('数学', '英語', '国語'),
  scores = c(80, 70, 90)
)

stringrを使った方法

tidyverseに入信したので、stringrを使います。

df %>% 
  mutate(subject = str_replace_all(
    subject,
    c('数学' = 'math', '英語' = 'english', '国語' = 'japanese')
  ))

置換できました。以下の方がスッキリしてますかね。

df$subject %>% 
  str_replace_all(c('数学' = 'math', '英語' = 'english', '国語' = 'japanese'))

余談

tidyverseはかなり使いやすいなと思いました。Rの基本パッケージのみだと使いにくいなと思っていたところなのでありがたい限りです。

7
9
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
7
9