簡體   English   中英

用變量重命名列名

[英]renaming column names with variable

我想用新名稱重命名特定列,該新名稱是dplyr的變量。

newName = paste0('nameY', 2017)

我試過的是

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

這使

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

我得到的是newName而不是nameY2017 ,這很正常。 所以我嘗試了

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

但是然后我得到一個錯誤。

錯誤:“虹膜%>%named_(eval(newName)=“

有使用dplyr的正確方法嗎? 我知道我可以做類似的事情

names(iris)[3] <- newName

但這不是dplyr解決方案。

dplyr“重命名”標准評估功能在此帖子中的功勞以及其他信息無法按預期運行?

您的代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM