Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slick one-lineRs [closed]

Tags:

r

What's your favorite one-liner in R?

Include a short companion example, and limit to one tip per post, please. Note, ; is cheating.

Example: calculate x[i] / x[i-1] for a vector x,

x <- 1:10
Reduce("/", as.data.frame(embed(x, 2)))

(collected from R-help, I forget who/when)

Edit: after some initial controversy, it looks like the question is now reopen for entries.


2 Answers

If you want to record the time that you created a file in its name (perhaps to make it unique, or prevent overwriting), then try this one-line function.

timestamp <- function(format = "%y%m%d%H%M%S")
{
  strftime(Sys.time(), format)
}

Usage is, e.g.,

write.csv(
   some_data_frame, 
   paste("some data ", timestamp(), ".csv", sep = "")
)
like image 124
Richie Cotton Avatar answered Sep 14 '25 10:09

Richie Cotton


Get odd or even indices.

odds <- function(x) seq_along(x) %% 2 > 0
evens <- function(x) seq_along(x) %% 2 == 0

Usage is, e.g.,

odds(1:5)
evens(1:5)
like image 42
Richie Cotton Avatar answered Sep 14 '25 10:09

Richie Cotton