Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a vector element by name in R when some names are duplicated

Tags:

r

vector

I had the vector x<-1:5 I named its elements (wrongly) names(x)<-rep(c(letters[1:4], "a")). How can I access the last element by name? x["a"] only return the first element named "a".

like image 670
Fabian Gil Avatar asked Jan 29 '26 05:01

Fabian Gil


1 Answers

How about:

x[names(x) == "a"]
# a a 
# 1 5 

Or to get only the final one:

x[tail(which(names(x) == "a"), 1L)]
# a 
# 5

This is more readable but marginally slower than getting at what tail does directly (see getAnywhere("tail.default")):

x[(idx <- which(names(x) == "a"))[length(idx)]
# a 
# 5
like image 100
MichaelChirico Avatar answered Jan 30 '26 20:01

MichaelChirico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!