Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

like image 927
Victor Van Hee Avatar asked May 18 '12 13:05

Victor Van Hee


People also ask

How do I combine vectors in R?

To concatenate two or more vectors in r we can use the combination function in R. Let's assume we have 3 vectors vec1, vec2, vec3 the concatenation of these vectors can be done as c(vec1, vec2, vec3). Also, we can concatenate different types of vectors at the same time using the same function.

How do I assign a name to a list in R?

The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them. Named list can also be created using names() function to specify the names of elements after defining the list.

How do you assign a value to a vector in R?

There are different ways of assigning vectors. In R, this task can be performed using c() or using “:” or using seq() function. Generally, vectors in R are assigned using c() function. In R, to create a vector of consecutive values “:” operator is used.

Which R function combines different values into a single object?

Concatenating Objects in R Programming – combine() Function Moreover, combine() function is used to combine factors in R programming.


1 Answers

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.

like image 187
jthetzel Avatar answered Sep 20 '22 16:09

jthetzel