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)
?
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.
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.
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.
Concatenating Objects in R Programming – combine() Function Moreover, combine() function is used to combine factors in R programming.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With