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!
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']
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