Code folding in RStudio: Creating hierarchy in the code

M. Beausoleil picture M. Beausoleil · Jun 15, 2016 · Viewed 9.8k times · Source

I'm writing R scripts in RStudio and I use the code folding a lot. I found that you can see the hierarchy of the folding by pressing cmd + shift + O. This is super helpful.

# to my dear love ---------------------------------------------------------
2+2 
# yo man ====
x.2 = function (x) {x+2}

### I do love potatoes ####

See the result by pressing cmd + shift + O.

enter image description here

I don't understand how this is working because when I write the code below, I can create a subsection without text but not when there is text in it (using # ==== but not # yo man ====).

# to my dear love ---------------------------------------------------------
2+2
# ==== 

# yo man ====

### I do love potatoes ####
x.2 = function (x) {x+2}
data = "here is some data"

See the result by pressing cmd + shift + O. enter image description here

You can see that under # to my dear love --------------------------------------------------------- everything under is shifted to the right! This is cool!

  1. The question is thus, how could it be possible to create a hierarchy of sections that include text in it?
  2. Is it a peculiar package or Emac that is doing this? How can I create subsections, with text, and see the hierarchy in the cmd + shift + O box?
  3. How can I down shift a section (going to a higher section (say section 2) to a lower section (section 1), by decreasing the visual hierarchy in the right box?

Answer

Greg H picture Greg H · Feb 15, 2018

As per Chris's answer subheaders within functions

RStudio Code Folding hierarchy only works within function definitions and if-else structures. For example:

# Section 1 ----
a <- 1

testfunct1 <- function () {
# sect in function=====
  b <- 2
  c <- 3
}

# Section 2 #####
d <- 4

# Section 3 =======
e <- 5

testfunct2 <- function () {
  # sect in function 2 =====
  f <- 6
  testsubfunct2_1 <- function () {
  # sect in subfunction 2_1 -----
    if (a == 1) {
      # section in if ----
      g < 7
    } else {
      # section in else ----
      h = 8
    }
  } 
}

# Section 4 ####
j <- 9

Produces this outline:

Code Outline screenshot

I don't know why the if-else section labels do not line up.