Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. # Composing functions
  2.  
  3. DRY (Don't repeat yourself!). If writing essentially the same code more than once, make a function.
  4.  
  5. Functions should be designed to be simple, to always return the same outputs when given the same
  6. inputs, and to avoid the use of side effects (having effects in addition to returning an output)
  7.  
  8. ## Bad
  9.  
  10. ```
  11. #t_output_IT.R
  12. data <- read.data(...)
  13. filter <- "IT"
  14. if (filter == "IT"){
  15. filtered_data <- data %>% filter(...)
  16. }else if(filter == "SE"){
  17. filtered_data <- data %>% filter(...)
  18. }
  19. run_analysis(filtered_data)
  20.  
  21. #t_output_SE.R
  22. data <- read.data(...)
  23. filter <- "SE"
  24. if (filter == "IT"){
  25. filtered_data <- data %>% filter(...)
  26. }else if(filter == "SE"){
  27. filtered_data <- data %>% filter(...)
  28. }
  29. run_analysis(filtered_data)
  30. ```
  31. ## Good
  32.  
  33. ```
  34. #t_output.R
  35. data <- read.data(...)
  36. filter_data <- function(datain, filter){
  37. if (filter == "IT"){
  38. return(datain %>% filter(...))
  39. }
  40. if(filter == "SE"){
  41. return(datain %>% filter(...))
  42. }
  43. }
  44. t_output <- function(datain, filter){
  45. filtered_data <- filter_data(datain, filter)
  46. run_analysis(filtered_data)
  47. }
  48. t_output(data, "SE")
  49. t_output(data, "IT")
  50. ```
  51.  
  52. Note that in this example I could probably take my filter_data function and use it in multiple
  53. different files now, while before I would need to copy and paste it everywhere!
  54.  
  55. # Code style
  56.  
  57. Truncate all lines at 80 characters (In RStudio: Tools - Global Options - Code - Display - Show Margin (Margin column = 80))
  58.  
  59. Make blank lines between code chunks (eg, between functions, etc) for better readability
  60.  
  61. Use comments to say WHY not WHAT.
  62.  
  63. ## Naming functions/objects
  64.  
  65. Try not to name things like df1, df2, temp1, temp2, etc. Take time to name things more properly (not easy!)
  66.  
  67. Suggestion: for functions, use verb_noun construction, e.g. derive_baseline, get_data
  68.  
  69. Avoid using "." in R names, as S3 methods make use of the ".", so this can confuse.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement