1

I would like to add a column for every element of a vector. The column value will be based on some criteria. I have used get() inside of filter() but it does not work inside of mutate().

Here is an example:

df <- read.table(text =
"A   B    C
1     2     3 
4     5     6
7     8     9",
header = TRUE, stringsAsFactors = FALSE)

I then use a function to go through the vector. Here is an example of just sending one character string

ID_function = function(var_name){

  df = df%>%
    mutate(get(var_name)=A + B)
}

ID_function("TEST")

The error is:

Error: unexpected '=' in:
"  df = df%>%
    mutate(get(var_name)="

Is there another method I could use?

Bryan Adams
  • 174
  • 1
  • 12

1 Answers1

2

We can use the assignment operator (:=) instead of <- and evaluate (!!) the string to create the column in tidyverse

library(tidyverse)
ID_function = function(var_name){

  df %>%
       mutate(!!var_name := A + B)
     }

ID_function("TEST")
#    A B C TEST
#1 1 2 3    3
#2 4 5 6    9
#3 7 8 9   15
akrun
  • 874,273
  • 37
  • 540
  • 662