Pankaj Agarwal Pankaj Agarwal - 2 months ago 8
R Question

Accessing element in named vector in R without variable name

I am trying to access the value of an element in a named character vector in R. Using the example in
http://www.r-tutor.com/r-introduction/vector/named-vector-members
I tried the following:

v = c("Mary", "Sue")
v
[1] "Mary" "Sue"
names(v) = c("First", "Last")
v
First Last
"Mary" "Sue"
v["First"]
First
"Mary"


I would like this to return "Mary" without the name "First" (and that is what is shown in the tutorial above), but when I try it always gives the name along with the value. I tried to set it to a variable, hoping it would give just the value

> teststr = v["First"]
> teststr
First
"Mary"
>


But I still get the variable name (First) along with the value.
I tried the following, but it gives back the same - value along with the element name.

>
> v[names(v)=="First"]
First
"Mary"
>


The data I have from my work project also produces the same results.
Would appreciate help with just getting "Mary" without "First".

Thanks - Pankaj

Answer

You can use unname

> unname(v["First"])
[1] "Mary"

Also, you can use getElement as an alternative

> getElement(v, "First")
[1] "Mary"