Home > Software design >  Assigning names to a vector retrieved by get()
Assigning names to a vector retrieved by get()

Time:06-21

I'm having issues with giving a vector object names when the vector itself is retrieved by get. This is a very simple example of my problem. Obviously the object_names object here isn't doing anything specific but in my actual script it just pertains to what actually goes into the scores and names objects and is working perfectly fine.

object_names <- c('test1', 'test2', 'test3')
for (n in object_names) {
  assign(paste0(n, '_scores'), 1:5)
  assign(paste0(n, '_names'), letters[1:5])
  names(get(paste0(n, '_scores'))) <- get(paste0(n, '_names))
}

When I run this I get the following error

Error in get(paste0(n, "_scores")) <- `*vtmp*` : 
  could not find function "get<-"

If I go back and just type out the command myself after the fact it obviously works, but I'd prefer to be able to do this in a more automated fashion. Is there perhaps a way to use assign() function to set the names attribute of a vector? Does anyone have any suggestions?

CodePudding user response:

You don't need get here at all:

object_names <- c('test1', 'test2', 'test3')

for (n in object_names) {
  scores <- 1:5
  names(scores) <- letters[1:5]
  assign(paste0(n, '_scores'), scores)
  assign(paste0(n, '_names'), names(scores))
}

test1_scores
#> a b c d e 
#> 1 2 3 4 5

test1_names
#> [1] "a" "b" "c" "d" "e"

Note though, that if you have a bunch of similar objects with similar names, you will save yourself a lot of time and effort if you put your objects in lists rather than assigning them to the global environment:

object_names <- c('test1', 'test2', 'test3')

setNames(lapply(object_names, function(x) setNames(1:5, letters[1:5])),
         paste0(object_names, "_score"))
#> $test1_score
#> a b c d e 
#> 1 2 3 4 5 
#> 
#> $test2_score
#> a b c d e 
#> 1 2 3 4 5 
#> 
#> $test3_score
#> a b c d e 
#> 1 2 3 4 5

Created on 2022-06-20 by the reprex package (v2.0.1)

  • Related