'How to add new column with variable using mutate
How to add new column with variable? I have a problem must use variable to add column.
library(dplyr)
data(iris)
x<-"newcol"
iris %>% mutate(x="only test") %>% head()
After running the above code, the new added column's name is x
, not expect newcol. how to fix it?
Solution 1:[1]
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
iris %>%
mutate(newcol = "test") %>%
head()
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species newcol
#> 1 5.1 3.5 1.4 0.2 setosa test
#> 2 4.9 3.0 1.4 0.2 setosa test
#> 3 4.7 3.2 1.3 0.2 setosa test
#> 4 4.6 3.1 1.5 0.2 setosa test
#> 5 5.0 3.6 1.4 0.2 setosa test
#> 6 5.4 3.9 1.7 0.4 setosa test
Created on 2022-05-06 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Carl |