16
11

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 3 years have passed since last update.

【R】[dplyr] rename()の中で変数を使う

Last updated at Posted at 2017-09-06

dplyr::rename(new = old)の中で変数を使うとき

もんだい

dplyr::rename(new=old)を関数の中などで使う際に、newに変数を使いたい場面があります

rename.R
varname <- "new_varname"
df <- iris

df %>% 
  rename(varname = Sepal.Length) %>% 
  colnames()

このままだとvarnameが変数("new_varname")ではなく文字列の"varname"として扱われてしまいます

[1] "varname" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"

かいけつさく

特別な代入演算子を使います
Pass a variable to dplyr "rename" to change columnname

rename.R
varname <- "new_varname"
df <- iris

df %>% 
  rename(!!varname := Sepal.Length) %>% 
  colnames()

image.png

メモ

以前の記事では以下のように書いていたのですが、rename_() is deprecated. とのことなので更新いたしました。

rename_()を使えば、変更前の変数名に関数を使ってもアクセスできるようです.

image.png

16
11
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
16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?