-1

I have two name columns. They look like this

name.a <- c("SPIDER MAN","SUPER MAN","BAT MAN") 
name.b <- c("SNOW WHITE","SPIDER MAN","SHELDON COOPER")
y <- cbind(name.a, name.b)

I want to search for each characters from name.a in name.b, and return the index. For example, I want to search for "SPIDER MAN" in name.b, get the result 2. Then do the same for "SUPER MAN" and "BAT MAN".

My failed attempt is

a <- c()
for (i in 1:dim(y)[1]){
  for(j in 1:dim(y)[1]){
    if (x[,2][j] == x[,1][i]){a <- c(a,i)}
  }
}

I have also used grep, but that did not work either.

Please note that I’m trying to search for a list of names. I know how to search for one name using grep, but assuming I have more than 2000 names in name.a, I don’t want to use grep more than 2000 times. When used grep in a for loop, the error I get is “Error in a[i]<-grep(y$name.a[i], y$name.b) :replacement has length zero

So it’s not a duplicate post since the previous doesn’t show how to search for a list of names

YCM
  • 7
  • 2
  • Pretty sure this is just `match` - `match(y[,"name.a"], y[,"name.b"])` if you are looking to do exact matches only. – thelatemail Nov 29 '17 at 04:36

1 Answers1

1

The grep way:

name.a <- c("SPIDER MAN","SUPER MAN","BAT MAN") 
name.b <- c("SNOW WHITE","SPIDER MAN","SHELDON COOPER")
y <- cbind(name.a, name.b);


grep("SPIDER MAN", y[, 2]);
#[1] 2

The match way:

match("SPIDER MAN", y[, 2]);
#[1] 2

The which way:

which(y[, 2] == "SPIDER MAN")
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • I know how to do it one by one, but I was trying to write a for loop so I don’t have to search one by one. – YCM Nov 29 '17 at 14:12
  • @YCM In that case your question is neither clear nor is your example representative (you only have one match). In any case, there's no need for a `for` loop. Just use e.g. `lapply`/`sapply` with `grep`, or `match` as in thelatemail's comment. – Maurits Evers Nov 29 '17 at 20:27