2017-05-23 7 views
1

dplyrに変数として指定された新しい名前で特定の列の名前を変更したいとします。私が試したことは変数名を列名に変更

Sepal.Length Sepal.Width newName Petal.Width Species 
     5.1   3.5  1.4   0.2 setosa 
     4.9   3.0  1.4   0.2 setosa 

を与える

iris %>% 
    rename(newName = Petal.Length) %>% 
    head(2) 

newName = paste0('nameY', 2017) 

私は通常であるnewNameないnameY2017を取得しています。だから私は試しました

iris %>% 
    rename_(eval(newName) = 'Petal.Length') 

しかし、私はエラーが発生しています。

Error: unexpected '=' in "iris %>% rename_(eval(newName) ="

dplyrで適切な方法はありますか? 私は

names(iris)[3] <- newName 

ような何かを行うことができます知っているしかし、それはdplyr解決策ではないでしょう。

+0

:h ttps://stackoverflow.com/questions/36520813/r-dplyr-rename-and-select-using-string-variable –

+0

あなたは '名前(アイリス)[どの名前(アイリス)%%で" newName "を試しましたか? ] < - paste0( 'nameY'、2017) 'です。 'dplyr'ではなく、うまくいくはずです。 – csmontt

答えて

2

クレジットとは、この記事ではさらに詳しい情報このdplyr 'rename' standard evaluation function not working as expected?

あなたのコード:

newName = paste0('nameY', 2017) 
iris %>% 
    rename(newName = Petal.Length) %>% 
    head(2) 

ソリューション:

iris %>% 
    rename_(.dots = setNames("Petal.Length",newName)) %>% 
    head(2) 

出力:これはここで回答されている

Sepal.Length Sepal.Width nameY2017 Petal.Width Species 
1   5.1   3.5  1.4   0.2 setosa 
2   4.9   3.0  1.4   0.2 setosa