考慮這個著名的表(已經存在于 R 中)
head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
請注意,它有一個名為 Sepal.Length 的列。我定義了一個同名的變數。請考慮以下代碼:
table = iris
Sepal.Length = 0
table2 = table %>% mutate ( new = Sepal.Length*Petal.Length )
如果檢查結果:
head(table2)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species new
1 5.1 3.5 1.4 0.2 setosa 0.28
2 4.9 3.0 1.4 0.2 setosa 0.28
3 4.7 3.2 1.3 0.2 setosa 0.26
4 4.6 3.1 1.5 0.2 setosa 0.30
5 5.0 3.6 1.4 0.2 setosa 0.28
6 5.4 3.9 1.7 0.4 setosa 0.68
如您所見,變數 Sepal.Length = 0 已被忽略,并且列 table$Sepal.Length 已被考慮用于創建新列。
如何在 mutate 函式的計算中使用變數?
uj5u.com熱心網友回復:
如果我們想使用 Global env 中的物件,它也是資料中的列名,請使用.env
library(dplyr)
table2 <- table %>%
mutate ( new = Petal.Width* .env$Sepal.Length )
uj5u.com熱心網友回復:
或者,按照此處所述放在!!前面https://stackoverflow.com/a/47659705/13015865Sepal.Length
包
library(dplyr)
解決方案
table <- iris #no need to change the name of the dataset. But ok.
Sepal.Length <- 0
table %>% mutate ( new = !!Sepal.Length*Petal.Length )
輸出(頭)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species new
1 5.1 3.5 1.4 0.2 setosa 0
2 4.9 3.0 1.4 0.2 setosa 0
3 4.7 3.2 1.3 0.2 setosa 0
4 4.6 3.1 1.5 0.2 setosa 0
5 5.0 3.6 1.4 0.2 setosa 0
6 5.4 3.9 1.7 0.4 setosa 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/435624.html
