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

r

Solution

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.

Problem

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)`?

Original source