0

Now I'm using R to find some of my indexing.

I use 2 for loop, and they are all needed.

So

for (n in 1:5){
  for(m in 1:15){
    if(length(grep(m,save))==1){ do sth
    }
  }
} 

save is list which contains 5 lists with numeric like this:

[[1]] [1] 1 4 8

[[2]] [2] 2 5 9

[[3]] [1] 3 6 10

[[4]] [1] 11 12

[[5]] [1] 7 13 15

Now I want to find match the number in o with numeric in save

What I mean is when o is 1,4,8 then it matched when n is 1! (list 1) but the problem is when m is 1 when n is 4 (list 4) 11, 12 also be found because it contains exactly '1' in 11, 12!

But I want only exactly find '1' not '11', '121', '333331'.. like that.

How can I do this with my code..? Indexing using two separate procedure is needed for me.

So if you know any answer about it, please give me a reply. Thank you

MLavoie
  • 9,671
  • 41
  • 36
  • 56
user13232877
  • 205
  • 1
  • 9

2 Answers2

1

I do not understand your question fully. I recommend providing a reproducible example.

However, I am guessing here you are not grep-ing the digits properly. Try a more specific regex. See this cheatsheet by RStudio. Also, I recommend {stringr} package.

library(stringr)

# extract 1 digit only, first matching
str_extract("1aa33", "\\d{1}")
>> 1

# extract 1 digit at the end of string
str_extract("1aa33", "\\d{1}$")
>> 3

# # extract 1 or more digits at the end of string
str_extract("1aa33", "\\d+$")
>> 33
Thomas Jc
  • 137
  • 2
  • Because I don't have mothertounge in english, so my explanation is quite hard for you. Sorry for it. but I'll confer your reply and it will really help me to develop my skills. Thank you. – user13232877 Apr 10 '20 at 03:56
0

This sure can be optimized but it is difficult without knowing more context. You also say you need two loops so without changing anything you can get your expected behavior by adding word boundaries in grep if I have understood it correctly.

for (n in 1:5){
   for(m in 1:15){
    if(length(grep(paste0('\\b', m, '\\b'),save))==1){ 
      #do something
    }
  }
} 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you. It is really well worked. I solved my problem. But when I examine my code, I mean, paste0("\\b",m,"\\b") then it returns "\\b1\\b" (when m is 1). And even it contains \\b in both sides, it works well when use grep(paste0('\\b', m, '\\b'),save[[1]]). How it happens? even \\b in pattern, but applied in vector 1 4 8 it finds exactly '1'. Again thanks for your reply. sincerely. – user13232877 Apr 10 '20 at 03:54
  • `\\b` is for word boundary meaning it looks for an exact match in the string. See the difference in output for `grepl('\\b1\\b', '1 person')` and `grepl('\\b1\\b', '124 person')` – Ronak Shah Apr 10 '20 at 04:07