U. Windl
U. Windl

Reputation: 4325

What is the shortest way to create an empty named numeric vector in R?

I can create an empty vector with v <- numeric(0), but the vector is not named, just of type num then. When I evaluate names(v) <- character(0), I have an empty named numeric vector:

> v <- numeric(0)
> names(v) <- character(0)
> str(v)
 Named num(0) 
 - attr(*, "names")= chr(0) 
> v["test"] <- 1
> str(v)
 Named num 1
 - attr(*, "names")= chr "test"

Is there an easier way to create the empty named numeric vector? It seems there is no constructor like named(0), or did I miss it?

Upvotes: 3

Views: 2232

Answers (1)

U. Windl
U. Windl

Reputation: 4325

Answers that can be derived from Create a numeric vector with names in one statement? are:

  1. Using structure().
  2. Using setNames().

For example:

> v <- structure(numeric(0), names=character(0))
> str(v)
 Named num(0) 
 - attr(*, "names")= chr(0) 


> v <-setNames(numeric(0), character(0))
> str(v)
 Named num(0) 
 - attr(*, "names")= chr(0) 

Upvotes: 2

Related Questions