select from list using starsWith

Hello,
I need to select the variable names from a data frame (genex) that start with "klox", "opiu", or "traj".
I wrote something like:

list_1=as.vector(names(genex))
names_1=list_1[startsWith(list_1, c("klox", "opiu",  "traj") )]

However, when I see the results from names_1, I notice that only some conditions are applied.
I don't know what I'm doing wrong.
Is there any other way to solve this?}
Thanks for your time, interest, and replies.}

can you please provide the output to list_1 and names_1? Also, I believe names() function generally outputs a vector, so I'm not sure you need to wrap it in the as.vector() function.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

I can't. I'm using a private database.
That's the reason I posted a generic syntax.
Using as.vector(names(... or just names(basex..directly doesn't make any difference in the results...
Maybe using grepl over the names(basex)...?

The code seems ok. I created an contrived list_1 as an example, and I'm getting the right output. The only thing I would say is to make sure that the elements of names(genex) that you are trying to extract in fact do start with the text that you believe they start with (i.e., no spaces before the word and correct spelling and correct case, etc.).

> list_1 = c("kloxic", "opium",  "trajectory", "opip", "tram")
> names_1 = list_1[startsWith(list_1, c("klox", "opiu",  "traj") )]
> names_1
[1] "kloxic"     "opium"      "trajectory"

You can also try the code below:

grep(x = list_1, pattern = "^(klox|opiu|traj)", value = TRUE)

Hope that helps,
Snehal