Melanie Julia
Melanie Julia

Reputation: 83

R: Subset vector by names

I have a vector with different names and its values. It is called composite:

GSM12    GSM13   GSM15   GSM16  GSM17
0.1234   9.345   8.888   5.345  1.234

And I have a second vector with names which are important.I only want those names with its values. The other names could be deleted. The vector is called biopsies.

GSM12  GSM15   GSM16

The result should be like this:

GSM12    GSM15   GSM16
0.1234   8.888   5.345

I tried the subset() function but it didn't work. I also tried this:

composite[apply(sapply(biopsies, grepl, composite), 1, any)]

But it also didn't work. So how can I do it? Thanks

Upvotes: 2

Views: 1716

Answers (1)

Edgar Santos
Edgar Santos

Reputation: 3514

x <- c(0.1234,   9.345,   8.888,  5.345,  1.234)
names(x) <- c("GSM12",  "GSM13",   "GSM15",   "GSM16",  "GSM17")
y <- c("GSM12", "GSM15",  "GSM16")

as @Gregor mentioned:

x[y]

 GSM12  GSM15  GSM16 
0.1234 8.8880 5.3450 

Upvotes: 5

Related Questions