-1

I have a list that looks something like this:

x=list(a=a,b=b,b1=b1,b2=b2,b3=b3,...,bn=bn,c=c)

I want to retrieve all the bn's by calling x$bn but the problem I have over here is that I don't know what is n (n varies across the different variables). Can someone give me a hint or two on how I should approach this problem?

OinkOink
  • 63
  • 1
  • 7
  • 1
    Maybe something with `grepl` can help. Can you give a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) ? – Ronak Shah Jun 29 '17 at 02:13

1 Answers1

2

You can use names(x) to get a character array and then llok for the biggest "bn" there.

Let's start by creating a list like you mentioned above with n=12

n = 12

x <- list(a = "a", c = "c")
for (i in 1:n)
  x[paste0("b", i)] <- i

Now we can use substr to find all the variable names that begin with "b"

nms <- names(x)
nms
# [1] "a"   "c"   "b1"  "b2"  "b3"  "b4"  "b5"  "b6"  "b7"  "b8"  "b9"  "b10"
# [13] "b11" "b12"
nms <- nms[substr(nms, 1, 1) == "b"]
nms
# [1] "b1"  "b2"  "b3"  "b4"  "b5"  "b6"  "b7"  "b8"  "b9"  "b10" "b11" "b12"

From this vector, we can now take the last entry and call the list

nam <- nms[length(nms)]
nam
# "b12"

bn <- x[nam]
bn
# 12
Gregor de Cillia
  • 7,397
  • 1
  • 26
  • 43