Well-written code is, among other things, easy to read. It has consistent indentation and formatting style. The opposite has been termed spaghetti code. Unlike Python, R has no official style guide. But, if there is something that comes close to it, then that’s Google’s R Style Guide. Some major players often formalize their own style, but generally base it off Google’s style.
Picking a style that makes sense and applying it consistently makes collaboration with others, getting answers on Stack Overflow, and understanding your own code a few months from now much easier, just as spelling grammar when writing in human languages. (reDzing mzzy kód IZ PNfol.)
In this exercise set, your task is take the snippets of code provided below and adopt them so they are consistent with good practices, and particularly, with Google’s style guide.
Solutions are available here.
Exercise 1
df= iris df[,2]
Exercise 2
"b">"a"
Exercise 3
Time <-"2017-11-29 18:31:49" substr(as.character(Time ),1,2) > 19
Exercise 4
y <- c(1,213,1235,1234,123,123,123,123,0) data.frame(x= sample(1:10, 9),y = rnorm ( 3^3), k = seq(9)* 34, hrut = ifelse(y > 100, 34,9))
Exercise 5
x =c(10 ,NA,15, 31) mean (x, na.rm=T)
Exercise 6
x=3 if(x==3){ print ( "x is 3") }
Exercise 7
stu=4;stur=sqrt(stu);stur
Exercise 8
fun1 = function() { sample(seq(4),2)#draw two numbers }
Exercise 9
HeIGHt__g <- 3 if (HeIGHt__g < 2) { print("Less than 2") } else { print("Not less than 2") }
Exercise 10
is_prime <- function (n) { if(n==2L) { return(T) } else { for (d in 2L:max(2L, n - 1L)) { if((n %% d) == 0) { return(F) } } } T }
Leave a Reply