Christoph Hanck
Christoph Hanck

Reputation: 353

remove names of several objects in R

I have many irregularly named objects whose names, in order to be able to use some other package, I need to set to NULL.

E.g.,

v <- 1
w <- 2
names(v) <- "hello"
names(w) <- "world"

I can write

names(v) <- names(w) <- NULL

but for succinctness I would prefer something like

names(c(v,w)) <- NULL

which however does not work ("Error in names(c(v, w)) <- NULL : could not find function "c<-"). This is not unexpected, of course - from ?names: it is a function "to get or set the names of an object".

Upvotes: 1

Views: 38

Answers (1)

akrun
akrun

Reputation: 887301

One option is to place it in a list and set the names to NULL. It is better not to have multiple objects in the global environment

lst1 <- lapply(list(v = v, w = w), setNames, NULL)

Also, as @joran mentioned, unname can be used as well or as.vector (which remove the attributes)

lst1 <- lapply(list(v = v, w = w), unname)

If the intention is to change the already existing objects,

list2env(lst1, envir = .GlobalEnv)
v
#[1] 1

It is better not to create multiple objects in the global env

Upvotes: 3

Related Questions