spindoctor
spindoctor

Reputation: 1913

Is there a way to select a range of elements in a named vector in R?

Is there a way to select a range, as opposed to specific, elements from a named vector in R?

vec<-c(1, 2, 3, 4, 5 )
names(vec)<-c('Jan', 'Feb', 'Mar', 'April', 'May')

vec['Jan']
#Something along these lines?
vec['Jan':'Feb']

Upvotes: 1

Views: 1886

Answers (3)

akrun
akrun

Reputation: 887951

We can use match from base R with : to get the sequence of index from the start and end based on the names of the vector and subset the vec

vec[match('Jan', names(vec)):match("April", names(vec))]
#   Jan   Feb   Mar April 
#   1     2     3     4 

Upvotes: 2

Liman
Liman

Reputation: 1300

A solution using dplyr.

library(dplyr)

unlist(data.frame(t(vec)) %>% select(Jan:April), use.names = TRUE)

# Jan   Feb   Mar April 
# 1     2     3     4 

Upvotes: 1

Duck
Duck

Reputation: 39613

Maybe this:

#Option 1
vec[names(vec) %in% c('Jan','Feb')]

Output:

Jan Feb 
  1   2 

Or this:

#Index
initial <- 'Jan'
last <- 'Feb'
i1 <- which(names(vec)==initial)
i2 <- which(names(vec)==last)
#Option 2
vec[i1:i2]

Output:

Jan Feb 
  1   2 

And some test:

#Test
initial <- 'Jan'
last <- 'April'
i1 <- which(names(vec)==initial)
i2 <- which(names(vec)==last)
#Option 2
vec[i1:i2]

Output:

  Jan   Feb   Mar April 
    1     2     3     4 

You would have to define initial and last in order to set the range.

Upvotes: 0

Related Questions