2

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

  • 10
    If it's a named vector and a vector of names, `composite[biopsies]` should work. If it doesn't work, then you should make a [reproducible example](http://stackoverflow.com/q/5963269/903061) so that we can tell what data structures you have. – Gregor Thomas May 04 '17 at 21:00
  • It may not be an elegant alternative, but have you tried something with `ifelse`? – elcortegano May 04 '17 at 21:07
  • @Gregor Thank you! That's it! – Melanie Julia May 04 '17 at 21:14

1 Answers1

5
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 
Edgar Santos
  • 3,426
  • 2
  • 17
  • 29