1

I have several objects in my global environment. I want to create a list of some of the objects in my environment. The objects that I want specifically have the two underscores in their names and p with a number at the end of it. For instance, this is an example of the names I have; "mom_big_p1", "mom_big_p2", "mom_big_p3", "mom_small_p1", "mom_small_p2", "mom_small_p3" and so on. There are other objects that have two underscores in their name like "mom_big_rank" but the only ones that have "name_size_p$" are the ones that I want.

When I try:

mom_size <- setNames(lapply(ls(pattern=".\\_p"), function(x) get(x)), ls(pattern=".\\_p")) 

I get all of the objects I want but I also get objects that have only one underscore and a p after the underscore. Is there a way to match a pattern of two underscores with a string in between them?

2
  • 1
    Some "^[[:alnum:]]+_[[:alnum:]]+_[[:alnum:]]*[[:digit:]]+$" should do the job. Or, "^[[:alnum:]]+_[[:alnum:]]+_p[[:digit:]]+$" if the part before the last number is fixed. Commented Sep 15, 2019 at 19:33
  • if pat is the pattern then use mget(ls(pattern = pat), envir = .GlobalEnv) Commented Sep 15, 2019 at 19:57

1 Answer 1

5

Sample environment:

vec <- c("mom_big_p1", "mom_big_p2", "mom_big_p3", "mom_small_p1", "mom_small_p2", "mom_small_p3", "mom_big_rank") sapply(vec, assign, 1, env=environment()) ls() # [1] "mom_big_p1" "mom_big_p2" "mom_big_p3" "mom_big_rank" "mom_small_p1" "mom_small_p2" # [7] "mom_small_p3" "vec" 

List objects that match your pattern:

ls(pattern = "_.+_p\\d+$") # [1] "mom_big_p1" "mom_big_p2" "mom_big_p3" "mom_small_p1" "mom_small_p2" "mom_small_p3" 

If you need something before the first underscore, try a pattern of ".+_.+_p\\d+$".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.