Select items in the named vector

I start with R and I cannot figure out how to do this:

I have a named vector with player names and its 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")

I need to get ratings for players whose name begins with the letter "A".

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

Thank!

+4
source share
1 answer

One of the methods -

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

^denotes the beginning of a line in a regular expression. greplwill return a logical vector that allows indexing fromx

Or (as pointed out in the comments) you can avoid the regex and do

x[substr(names(x), 1, 1) == 'A'] 
+4
source

Source: https://habr.com/ru/post/1584026/


All Articles