0

I am not a pro, so please excuse my messy code, however, I cannot solve this error I keep getting. I am trying to pull data from a different table (CompMeta) to annotate the 'company category' based on the 'company name' using a for loop and grep.

I used the following code in R:

for (i in 1:length(df5$Company1)) {
  df5$type[i] <- CompMeta$`Company Category`[grep(df5$Company1[i],CompMeta$Company)]
}

Unfortunately I am getting this error and can't really figure out why:

Error in df5$type[i] <- CompMeta$`Company Category`[grep(df5$Company1[i],  : 
  replacement has length zero

If I just test it with a number instead of i, the grep function works fine! Would be really great if someone could help me out here!

Best Talata

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Talata
  • 1
  • 1
  • 2
    It seems likely that something is spelled wrong or is the wrong data type, but since we don't know what's in any of these variables it's hard to tell. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Also it kind of looks like you should be using `merge()` here rather than a loop. It would probably do what you want much more easily. – MrFlick Nov 30 '22 at 17:56
  • 2
    In short, at least one time `grep()` doesn't come up with a match (it has a length 0 result), and you can't assign "nothing" to something. You could do a missing value instead, or maybe there always should be a match and it's a bug in your code. Hard to say without seeing some sample data. – Gregor Thomas Nov 30 '22 at 18:01
  • Thanks a lot! Obviously I could just use merge(), or leftjoin()... thanks for pointing that out, it's obviously been too long since I used R... – Talata Nov 30 '22 at 19:37

0 Answers0