Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
nilforooshan / duplicated_example.md
Last active September 26, 2024 23:37
R: duplicated example

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))
@nilforooshan
nilforooshan / function_within_function.md
Last active March 30, 2019 08:59
R: Use a function within another function

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")))
@nilforooshan
nilforooshan / capture_error.md
Last active March 30, 2019 08:58
R: Capture Rscript errors in an output file

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:

@nilforooshan
nilforooshan / RW_fwf.md
Last active March 30, 2019 08:57
R: Read and write fixed width files (fwf)

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
@nilforooshan
nilforooshan / long_loop_counter.md
Last active October 3, 2024 02:34
R: Count number of iterations by 100

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")
@nilforooshan
nilforooshan / is_integer.md
Last active March 30, 2019 08:56
R: Getting around the problem with is.integer

Getting around the problem with is.integer

is.integer(1)

[1] FALSE

A new function:

@nilforooshan
nilforooshan / paste_cols.md
Last active March 30, 2019 08:54
R: Paste columns together in a new column

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
@nilforooshan
nilforooshan / odd_even_finder.md
Last active March 30, 2019 08:54
R: Find odd and even numbers

Find odd and even numbers

Functions:

is.even = function(x) x %% 2 == 0
is.odd  = function(x) x %% 2 != 0

Examples:

@nilforooshan
nilforooshan / col_with_NA.md
Last active March 30, 2019 08:53
R: Find columns containing missing value

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
@nilforooshan
nilforooshan / sample_color.md
Last active March 30, 2019 08:52
R: Sample random colours

Sample random colours

sample(colours(), 5)

[1] "gray26" "goldenrod3" "lightcyan1" "grey83" "grey9"