How do I create new variable names using argument in my function in R?

Viewed 67

This is a dataset.

require(data.table) 
df <- data.table(a = c(1, 2, 3),
b = c(4, 5, 6))
   a b
1: 1 4
2: 2 5
3: 3 6

I would like to make several several column names with my function.

Here is a example function.

 f_test <- function(x){
  
  variableName1 <- eval(paste0("variableName1_", x))
  variableName2 <- eval(paste0("variableName2_", x))
  
  print(variableName1)
  
  #setNames(variableName)
  
  df_1a <- df[, `:=` (variableName1 = a * b * 1,
                      variableName2 = a * b * 2)]
  
}

For example, this is the expected outcome from f_test("AAA")

   a b variableName1_AAA variableName2_AAA
1: 1 4                 4                 8
2: 2 5                10                20
3: 3 6                18                36

However, the function outcome is not 'variableName1_AAA', but 'variableName1'.

How do I assign the name based on the string argument in the function? I need to assign the name character to use in the future function work.

1 Answers

We can use paste directly to create the column names as the input is a string. The assignment (:=) can also be done with concatenating the column name objects on the lhs of :=

f_test <- function(x){

  variableName1 <- paste0("variableName1_", x)
  variableName2 <- paste0("variableName2_", x)

  df_1a <- copy(df)

  df_1a[, c(variableName1, variableName2) := .( a * b * 1,
                   a * b * 2)][]
  
                 

 }

-testing

f_test("AAA")
#   a b variableName1_AAA variableName2_AAA
#1: 1 4                 4                 8
#2: 2 5                10                20
#3: 3 6                18                36
Related