Victor Van Hee
Victor Van Hee

Reputation: 9919

In R, can't set names of vector elements using assignment in combine function

Quick question. Why does the following work in R (correctly assigning the variable value "Hello" to the first element of the vector):

> a <- "Hello"
> b <- c(a, "There")
> b
[1] "Hello" "There"

And this works:

> c <- c("Hello"=1, "There"=2)
> c
Hello There 
    1     2 

But this does not (making the vector element name equal to "a" rather than "Hello"):

> c <- c(a=1, "There"=2)
> c
    a There 
    1     2 

Is it possible to make R recognize that I want to use the value of a in the statement c <- c(a=1, "There"=2)?

Upvotes: 9

Views: 3851

Answers (2)

Dennis Warner
Dennis Warner

Reputation: 1

Assign the values in a named list. Then unlist it. e.g.

lR<-list("a" = 1, "There" = 2 )

v = unlist(lR)

this gives a named vector v

v

a There 
1     2 

Upvotes: 0

jthetzel
jthetzel

Reputation: 3623

I am not sure how c() internally creates the names attribute from the named objects. Perhaps it is along the lines of list() and unlist()? Anyway, you can assign the values of the vector first, and the names attribute later, as in the following.

a <- "Hello"
b <- c(1, 2)
names(b) = c(a, "There")
b
# Hello There 
#     1     2 

Then to access the named elements later:

b[a] <- 3
b
# Hello There 
#     3     2 
b["Hello"] <- 4
b
# Hello There 
#     4     2
b[1] <- 5
b
# Hello There 
#     5     2

Edit

If you really wanted to do it all in one line, the following works:

eval(parse(text = paste0("c(",a," = 1, 'there' = 2)")))
# Hello there 
# 1     2 

However, I think you'll prefer assigning values and names separately to the eval(parse()) approach.

Upvotes: 8

Related Questions