R tutorials

Few good practices in R programming






Presented by : Deepak Sharma
[ Use arrow keys to go to prev/next page ]

Few questions


  • Should you write code just to get your work done?
  • Do you need to care for reusability?
  • Do you write user friendly code as well as programmer friendly code?

Which coding style looks best?

All styles have same results, one is better other is best of all

  • Style 1
a <- 10
b <- 20
c <- (10+20)/2
c
[1] 15

Which coding style looks best?

All styles have same results, one is better other is best of all

  • Style 2
variable_number_1 <- 10 
variable_number_2 <- 20
third_variable <- mean(c(variable_number_1,variable_number_2))
print(third_variable)
[1] 15

Do profiling


# Try writing efficient programs (Save time)
numbers <- 1:10000000
system.time({ 
  total <- 0
  total <- sum(c(numbers))  # Vectorized code
  cat("Sum is : ",total,"\n")
})
Sum is :  5e+13 
   user  system elapsed 
   0.13    0.00    0.12 

Learn shortcuts - Save time


# Ctrl + Shift + C  # Comment selected lines
# Ctrl + Shift + R  # Insert section
# Ctrl + L  # Clear console
rm(list=ls())   # Clear all workspace variables
# Use an IDE such as RStudio
cat('\f') # To clear your console
# Press [`Alt` + `-`] to put <- or `assignment operator` in RStudio

Few useful links