0

If we have the following data.table:

x <- data.table(`2021` = rep(10, 3), `2022` = rep(5, 3))

we can create a new column like this:

x[, d := `2022` / `2021` -1]

Now I want to save 2022 and 2021 in a vector like this:

years <- c("2021", "2022")
x[, d := years[2] / years[1] -1]

but of course, this doesn't work. I tried to use eval and as.name but it doesn't work in that specific case. How can I achieve that?

3 Answers 3

3

With development version 1.14.3, has gained the new env argument (see the new vignette programming on data.table). So, the recommended way is

library(data.table) # development version 1.14.3 used here
years <- c("2021", "2022")
x[, d := yr2 / yr1 - 1, env = list(yr1 = years[1], yr2 = years[2])][]

or

x[, d := yrs[[2]] / yrs[[1]] - 1, env = list(yrs = as.list(years))][]

Both return

   2021 2022    d
1:   10    5 -0.5
2:   10    5 -0.5
3:   10    5 -0.5
Sign up to request clarification or add additional context in comments.

Comments

2

We could use .SD to subset

x[, d := .SD[[years[2]]]/.SD[[years[1]]] - 1]

Comments

1

Use get when you want to tell the data.table that you are referring to something inside its environment (the dt itself) or higher (see ?get)

x[, d := get(years[2])  / get(years[1]) -1]

1 Comment

Since I am not using the last data.table version as @Uwe suggest, I think this is the simplest solution.

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.