Bharat Ram Ammu
Bharat Ram Ammu

Reputation: 184

Run this line if above line runs error free in R

an example on why I need to run a line only if previous line doesn't produce an error: Consider the following example:

In a good case:

> vec<- c(1,2,3,4) # Have a basic vector index<- which(vec ==1) # index
> whose value is 1 logical<-grepl(index,vec) # logical if found index in
> vector element<-vec[logical] #find element which satisfies logical
> element #1 - good!

However in another case:

index<- which(vec ==5) #5 not present in vec
logical<-grepl(index,vec) #produces error: invalid pattern
element<-vec[logical] #but logical is still same as previous assignment
element # still 1 - because logical is retained

The problem I want to solve: how can I make sure the object 'logical' is not used in the 2nd case in the creation of object 'element', because the previous line didn't work and produced an error? Thanks in advance!

Upvotes: 0

Views: 52

Answers (1)

shwan
shwan

Reputation: 570

Check if index is a number before submitting?

logical <- ifelse(length(index) > 0,grepl(index,vec),FALSE)

Upvotes: 2

Related Questions