Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements in named vector

I'm a begginer with R and I can't figure out how to do this:

I have a named vector with player names and his score:

x <-c(3, 4, 6, 2, 3, 5, 0, 1, 1, 2)
names(x) <- c("ALBERTO", "ANTONIO", "PEPE", "JUAN", "ANDRES", "PEDRO", "MARCOS", "MATEO", "JAVIER", "FRANCISCO")

What I need is to get the scores for the players which name starts with letter "A".

Is it possible to set a condition on the element name?

Thank you!

like image 625
Nacho Avatar asked Apr 22 '15 13:04

Nacho


1 Answers

One way is

x[grepl("^A", names(x))]
# ALBERTO ANTONIO  ANDRES 
#       3       4       3 

^ stands for beginning of the string in regex. grepl will return a logical vector which will allow to index out of x

Or (as pointed in comments) you could avoid regex and do

x[substr(names(x), 1, 1) == 'A'] 
like image 195
David Arenburg Avatar answered Sep 19 '22 06:09

David Arenburg