0

I'm trying to name dataframes in lists. The lists are like d.list01, d.list02...

Suppose they contain two data.frame respectively, and trying to name them "A" and "B". I wrote a for-loop like...

name.vectro <- c("A", "B")
for (i in 1:8) {
  temp <- paste0("d.list", sprintf("%02d", i))
  names(eval(parse(text = temp))) <- name.vector
}

This returns an error:

> Error in names(temp) <- name.vector : 
>   target of assignment expands to non-language object

I tried some other ways such as...

  names(as.name(parse(text = temp))) <- name.vector

But I got the same error as above. I don't quite understand what "non-language object" is. I googled some related words, but I couldn't find related documents.

Any suggestions?

Any advice would be appriciated!

kei
  • 1
  • 1
  • 2
    You can't `eval(parse())` on the left-hand side of an assignment. The easiest way is to put your lists in a list, `d_list = mget(ls(pattern = "d.list[0-9]+"))` then `d_list = lapply(d_list, setNames, name.vectro)`. – Gregor Thomas Aug 28 '23 at 15:00
  • 2
    If you really want all the lists back in the global environment, you can follow @GregorThomas code then at the end do `list2env(d_list, .GlobalEnv)`, but for many reasons it would be best to keep all your lists in one big list (not least because it is easier to iterate over them all, exactly as you are trying to do here) – Allan Cameron Aug 28 '23 at 15:03
  • 2
    You could also use `assign(temp, setNames(get(temp),name_vector))`. But in general there are usually better options than using `eval/parse` or `get/set` in R. Using a named list rather than keeping a bunch of separate variables in the global environment is almost always easier to work with in code. – MrFlick Aug 28 '23 at 15:07
  • Thanks \@GregorThomas, \@AllanCameron and \@MrFlick! The comments helped a lot and worked fine. I'll read more the duplicated question. (Indeed, I'm not quite sure how they are related...!) – kei Aug 29 '23 at 04:45

0 Answers0