我想使用dplyr的mutate()
在數據框中創建多個新列。列名稱及其內容應該動態生成。從虹膜dplyr - mutate:使用動態變量名稱
示例數據:
require(dplyr)
data(iris)
iris <- tbl_df(iris)
我創建了一個函數從Petal.Width
變量變異我的新欄目:
multipetal <- function(df, n) {
varname <- paste("petal", n , sep=".")
df <- mutate(df, varname = Petal.Width * n) ## problem arises here
df
}
現在我創建一個循環來構建我的專欄:
for(i in 2:5) {
iris <- multipetal(df=iris, n=i)
}
但是,由於mutate認爲varname是一個字面變量名,該循環僅創建一個新變量(稱爲varname)而不是四個(稱爲petal.2 - petal.5)。
如何獲得mutate()
以將我的動態名稱用作變量名?
我沒有堅持在變異時,我問是否可能。也許這只是我不知道的一個小動作。如果還有其他方法,讓我們聽聽。 – 2014-09-23 20:11:20
我相信在[lazyeval包](https://github.com/hadley/lazyeval)中有[可以觀看的空間](https://github.com/hadley/dplyr/issues/352#issuecomment-53829862) – baptiste 2014-09-23 20:59:06
在這一點上,'dplyr'有一個[非標準評估整個小插曲](https://cran.r-project.org/web/packages/dplyr/vignettes/nse.html) – Gregor 2016-07-05 23:25:03