duplicated example A sample data: a <- c(rep("A",3),rep("B",3),rep("C",2)) b <- c(1,1,2,4,1,1,2,2) (df <- data.frame(a,b))
Use a function within another function Make a single function from multiple functions A sample data: (data <- data.frame(sire=c(rep("a",5),rep("b",5)), herd=c("c","c","d","d","d","e","e","f","f","g")))
Capture Rscript errors in an output file Error messages are not captured in the log file. To do so: Rscript --no-save --no-restore --verbose myRfile.R > outputFile.Rout 2> errorFile.Rout To put the output and error in the same file:
Read and write fixed width files (fwf) A sample data: (x.1 = data.frame(a=runif(6,1,1000), b=runif(6,1,1000), c=runif(6,1,1000), d=runif(6,1,1000), e=runif(6,1,1000))) a b c d e
Count number of iterations by 100 The following example reports every 100 iterations. final = 1234 for(i in 1:final) { if(i %% 100 == 0) cat(i, "of", final, "\n") } cat(i, "of", final, "\n")
Paste columns together in a new column A sample data: (mydf = data.frame(w = 1:3, x = c('a','b','c'), y = c('d', 'e', 'f'), z = c('g', 'h', 'i'))) w x y z
Find odd and even numbers Functions: is.even = function(x) x %% 2 == 0 is.odd = function(x) x %% 2 != 0 Examples:
Find columns containing missing value A sample data: (test1 <- data.frame (matrix(c(1,2,3,NA,2,3,NA,NA,2), 3,3))) X1 X2 X3