2

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
  • When I change that to your suggestion, the function does not work. Commented Apr 25, 2021 at 22:41

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.