1
votes

I want to extract a variable name from a data frame a create a new variable with dplyr::mutate. What do I have to write so that the variable name provided through "md$meta[1]" is accepted? I think this is straight forward but I haven't been able to find the answer on the web. Any help greatly appreciated!

Fake data

iris <- head(iris)
meta <- c("a", "b", "c")
data <- c(1:3)
md <- data.frame(meta, data)
rm(meta, data)

Desired output

iris <- iris %>%
  mutate("a" = md$data[1])

Code attempt

iris <- iris %>%
  mutate(paste0(md$meta[1]) = md$data[1])
1

1 Answers

3
votes

This can be done with assignment (:=) and by evaluating (!!) the lhs of the assignment

iris %>% 
    mutate(!! paste0(md$meta[1]) := md$data[1])
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species a
#1          5.1         3.5          1.4         0.2  setosa 1
#2          4.9         3.0          1.4         0.2  setosa 1
#3          4.7         3.2          1.3         0.2  setosa 1
#4          4.6         3.1          1.5         0.2  setosa 1
#5          5.0         3.6          1.4         0.2  setosa 1
#6          5.4         3.9          1.7         0.4  setosa 1