简体   繁体   中英

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM