0

I would like to assign variables to elements in a named list. These variable names are the same as the names in the list. Is there a way that I can assign them all in one line instead of one at a time like what I am doing below?

 params <- data[data$Month == m,]

  a <- params$a
  b <- params$b
  c <- params$c

I know that in Java Script you can destructure and array like so:

const [a, b, c] =[1,2,3]

Or a dictionary (which is perhaps more similar to an R named list):

const {a, b, c} = {a:1, b:2, c:3}

Each of these assign the variables a,b and c to the values 1,2 and 3 respectively.

Is there a similar approach that I can take with R?

Oamar Kanji
  • 1,824
  • 6
  • 24
  • 39
  • You should `dput` example data and specify expected output to clarify what you want, please consult our R-tag guidelines before posting: https://stackoverflow.com/a/5963610/6574038 – jay.sf Feb 25 '21 at 07:24

2 Answers2

1

Use list2env to create individual objects for each column in params.

params <- data[data$Month == m,]
list2env(params, .GlobalEnv)

If you want to keep data in a named list use as.list.

as.list(params)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Establish a named list (lst) in advance. Then you can assign the variables in the data frame (params) in one line.

lst <- vector(mode="list", length = 3)
lst <- list(params$a,params$b,params$c)
names(lst) <- c("a","b","c")
Sam
  • 13
  • 2