Domanda

I'd like to know if there's an easy way to find an intersection of two named vectors and output the result to a third, named vector.

In my case, I have the following two named vectors:

> test1
ATMG00010 ATMG00030 ATMG00040 ATMG00050 ATMG00060 ATMG00070 
  462       324       948       396       542       573 

> test2
ATMG00010 ATMG00040 ATMG00070 
    0         0         0 

What is the elegant way to find the intersection of the two vectors based on names and then output the name, value pair of test1 into a new named vector, test3?

i.e.,

> test3
ATMG00010  ATMG00040 ATMG00070 
  462         948       573 

In order for me to get on with my life, I found an intermediate solution that got the job done, but the result was not a named vector, just a numerical vector of values from matched names in test1.

matched <- which(names(test1) %in% names(test2))
test3 <- rep(NA, length(test2))
for (i in 1:length(matched)) { test3[i] <- c(test1[[matched[i]]]) }

This gives me the following result:

test3 [1] 462 948 573

As I only know a little bit of python and pretty much nothing about R, the above code was learned through an all day immersion process. Is there a more straightforward way to do this ?

Thank you!

È stato utile?

Soluzione

I presume you would like to return values of the test1 object:

test3 <- test1[intersect(names(test1),names(test2))]

intersect() outputs a character string with the names shared between the two vectors. By wrapping the resulting string within the square brackets, we can return matching elements of any vector, in this case test1.

Altri suggerimenti

library(dplyr)

test3 <- join(test1, test2)[, intersect(names(test1), names(test2))]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top