8.4 Developing Workflows with R Scripts

This section we’ll look at control flow, R scripts and workflows for working with many files and exporting data.

8.4.1 Control Flow: if, for, and while

Most of R’ task don’t require modifying control flow and we can replace them by functions like lapply(), sapply() and mapply(). But we need under some circumstances. The basic syntax of if, for and while are:

if (x == some_value) {
         # do some stuff in here
} else {
         # else is optional

for (element in some_vector) {
         #iteration happens here

while (something_is_true) {
         # do some stuff

Also, break to break out of for and while loops; next to advance loops to the next iteration.

It’ll be common to create a vector of indexes like:

for (i in 1:length(vec)) {
  # do sth

If the vector vec has no elements, it’s length is 0, and 1:0 would return the sequence 1, 0. We can use seq_along() to handle this:

 > vec <- rnorm(3)
 > seq_along(vec)
 [1] 1 2 3
 > seq_along(numeric(0))   # numeric(0) returns an empty numeric vector

seq_len(length.out) is similar and returns a sequence length.out elements long.

R has a vectorized version of if: the ifelse funciton. ifelse(test, yes, no) returns the yes value for all TRUE cases of test and no for all FALSE cases:

 > x <- c(-3, 1, -5, 2)
 > ifelse(x < 0, -1, 1)
 [1] -1 1 -1 1

11 Replies to “8.4 Developing Workflows with R Scripts”

  1. We stumbled over here by a different page and thought I might as well check things out.
    I like what I see so now i am following you. Look forward to finding out about your web page yet again.

  2. Its such as you learn my mind! You appear to grasp so much about this,
    such as you wrote the book in it or something. I believe that you simply could do with
    some percent to drive the message home a bit, however other than that,
    this is magnificent blog. An excellent read. I will certainly be back.

  3. Thanks for sharing excellent informations. Your web site is so cool. I am impressed by the details that you’ve on this web site. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for extra articles. You, my pal, ROCK! I found just the information I already searched everywhere and simply couldn’t come across. What a perfect site.

  4. The web site editorial writer includes a certain effortless skill to describe definitely good topics. Reads the web publication content is unquestionably huge and you’ll stumble on without doubt many conventional site visitors. No wonder, while using high-quality writing. In any circumstance, it was a delight to commit time on your site and study the out of the ordinary content.

Leave a Reply

Your email address will not be published. Required fields are marked *