Posts

Showing posts with the label R

Error Handling in R

Image
What is an Exception? An unwanted situation that may arise while your code is getting exected is called an Exception e.g when your code attempts to divide a value by zero. Exception Handling Exception handling is the process of handling the errors that might occur in the code and avoid abrupt halt of the code. In simple English, our code should either end by performing the intended task or prints a useful message if it is not able to complete the task. We have this code which has non-numeric value in the list and we are trying to divide  5 with every element of vector v #a list with one non numeric value v<-list(1,2,4, '0' ,5) for (i in v) { print(5/i) } Here we can see that the code has not printed any result and has stopped abruptly. To avoid these situations we use exception handling constructs available in R Exception Handling Constructs in R try tryCatch Using try We need to enclose the objectionable statements ...

Looping in R

Image
LOOPS in R Loops are part of iterative programming where the user wants to perform a sequence of instructions N number of times. R provides 3 styles of loops: For Loop While Loop Repeat Loop For Loop For loops are used when we want to iterate over a sequence like vectors and or data frames. Syntax: v<-c(10,21,11,31,88,78) for (i in v){       print(i) } This will iterate over all the elements of vector v. For iterating over individual elements using the index one can use sequence vector and use it as index. Syntax: v<-c(10,21,11,31,88,78) for (i  in  1:length(v)){       print(v[i]) } While Loop While loops are used when the iterations depend on a condition and it is difficult to predict the number of iterations. SYNTAX: i<-2 while(i<=10){          print(i)          i<-i+2 } Repeat Repeat is a new ...