0

Suppose I do something like the following:

x <- 'zeal'
t <- strsplit(x, '')
g <- unlist(t)
g
[1]"z" "e" "a" "l" 
r <- letters[(which(g[1] == letters))]
r
[1]"z"

My end goal for this is to have something where I can say "find the element in some variable which matches something so for example, if I had

e <- 'bacon'
e <- strsplit(e, '')
e <- unlist(e)
e
[1]"b" "a" "c" "o" "n"

then "find the element in e which matches "b"". And then apply that over until all elements in e are matched

Nolohice
  • 339
  • 4
  • 15
  • 4
    What is the desired output here? Can you describe what you are trying to do in words? – MrFlick Jun 18 '15 at 16:41
  • Hi, I've edited it with some further explanation, hopefully that helps. – Nolohice Jun 18 '15 at 16:59
  • You're still missing half your input and your desired output. "find the element in `e` which matches "b"", I see `e`, but where does "b" come from? are you doing all `letters`? – Gregor Thomas Jun 18 '15 at 17:14
  • Something like `sapply(letters, FUN = function(x) which(grepl(x, e)))`? – Gregor Thomas Jun 18 '15 at 17:17
  • I agree with Gregor, you are still missing importing information in your question. But maybe you are looking for `match()`? Maybe check out [how to make a great reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Maybe provide some sample function that you want to run on all the matches. – MrFlick Jun 18 '15 at 17:18

1 Answers1

1

I don't thing the sum does anything because each g element will only match once. Here you can you use an apply function instead of explicit loop as is standard in R. The variable i is like g[i] as you have it written.

sapply(g, function(i) letters[which(i == letters)])
Rorschach
  • 31,301
  • 5
  • 78
  • 129