3

Here is the simplified version:

Suppose I am using 'which' function to find a position, say -

position_num=which(df$word=="ABC")

If the value exists it is fine and it returns an integer, but in case it is unable to match it returns integer(0) in such a case I want to assign a default value to position_num=1.

Thanks for the help in advance

Anurag H
  • 909
  • 11
  • 28

2 Answers2

5

Something like the following if() statement would probably do it.

position_num = if(!length(w <- which(df$word == "ABC"))) 1 else w 

Here we are just checking to see if the result from which() has a length, because

length(integer(0))
# [1] 0

And we return 1 if it doesn't have a length, and the which() result (w) otherwise.

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • 2
    This one is much better than mine, because: 1. It does not call ifelse, which can be time consuming 2. It calls which() only once – Paweł Sopel Jan 30 '16 at 22:42
1

Would this work for you?

position_num=ifelse(length(which(df$word=="ABC")) != 0,which(df$word=="ABC"),1)
Paweł Sopel
  • 528
  • 4
  • 17