5

Everytime I open a new session in RStudio, I'm greeted with the error message:

Error: C stack usage  7953936 is too close to the limit

Based on suggestions for similar issues posted here and here, I tried using the ulimit command in terminal, but get the following error.

Isabels-MacBook-Pro ~ % ulimit -s
8176

Isabels-MacBook-Pro ~ % R --slave -e 'Cstack_info()["size"]'
Error: C stack usage  7954496 is too close to the limit
Execution halted

Yet, when I run ulimit on it's own, I get:

Isabels-MacBook-Pro ~ % ulimit
unlimited

Just to double-check, I try setting it to unlimited again:

Isabels-MacBook-Pro ~ % ulimit -s unlimited

but then get a new error:

Isabels-MacBook-Pro ~ % R --slave -e 'Cstack_info()["size"]'
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
Execution halted

I have no clue what this means in this context. Is the Cstack_info() the bit getting stuck on infinite recursion?? I'd love to get this figured out, as it's getting in the way of installing some necessary packages!

In case it's helpful, here's my session info

R version 4.1.3 (2022-03-10)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Monterey 12.2.1

And contents of .Rprofile

# REMEMBER to restart R after you modify and save this file!

# First, execute the global .Rprofile if it exists. You may configure blogdown
# options there, too, so they apply to any blogdown projects. Feel free to
# ignore this part if it sounds too complicated to you.
if (file.exists("~/.Rprofile")) {
  base::sys.source("~/.Rprofile", envir = environment())
}

# Now set options to customize the behavior of blogdown for this project. Below
# are a few sample options; for more options, see
# https://bookdown.org/yihui/blogdown/global-options.html
options(
  # to automatically serve the site on RStudio startup, set this option to TRUE
  blogdown.serve_site.startup = FALSE,
  # to disable knitting Rmd files on save, set this option to FALSE
  blogdown.knit.on_save = TRUE,
  # build .Rmd to .html (via Pandoc); to build to Markdown, set this option to 'm$
  blogdown.method = 'html'
)

# fix Hugo version
options(blogdown.hugo.version = "0.82.0")

Here are the contents from /Library/Frameworks/R.framework/Resources/library/base/R/Rprofile

### This is the system Rprofile file. It is always run on startup.
### Additional commands can be placed in site or user Rprofile files
### (see ?Rprofile).

### Copyright (C) 1995-2020 The R Core Team

### Notice that it is a bad idea to use this file as a template for
### personal startup files, since things will be executed twice and in
### the wrong environment (user profiles are run in .GlobalEnv).

.GlobalEnv <- globalenv()
attach(NULL, name = "Autoloads")
.AutoloadEnv <- as.environment(2)
assign(".Autoloaded", NULL, envir = .AutoloadEnv)
T <- TRUE
F <- FALSE
R.version <- structure(R.Version(), class = "simple.list")
version <- R.version            # for S compatibility

## for backwards compatibility only
R.version.string <- R.version$version.string

## NOTA BENE: options() for non-base package functionality are in places like
##            --------- ../utils/R/zzz.R

options(keep.source = interactive())
options(warn = 0)
# options(repos = c(CRAN="@CRAN@"))
# options(BIOC = "http://www.bioconductor.org")

## setting from an env variable added in 4.0.2
local({to <- as.integer(Sys.getenv("R_DEFAULT_INTERNET_TIMEOUT", 60))
    if (is.na(to) || to <= 0) to <- 60L
    options(timeout = to)
})
options(encoding = "native.enc")
options(show.error.messages = TRUE)
## keep in sync with PrintDefaults() in  ../../main/print.c :
options(show.error.messages = TRUE)
## keep in sync with PrintDefaults() in  ../../main/print.c :
options(scipen = 0)
options(max.print = 99999)# max. #{entries} in internal printMatrix()
options(add.smooth = TRUE)# currently only used in 'plot.lm'

if(isFALSE(as.logical(Sys.getenv("_R_OPTIONS_STRINGS_AS_FACTORS_",
                                 "FALSE")))) {
    options(stringsAsFactors = FALSE)
} else {
    options(stringsAsFactors = TRUE)
}

if(!interactive() && is.null(getOption("showErrorCalls")))
    options(showErrorCalls = TRUE)

local({dp <- Sys.getenv("R_DEFAULT_PACKAGES")
       if(identical(dp, "")) ## it fact methods is done first
           dp <- c("datasets", "utils", "grDevices", "graphics",
                   "stats", "methods")
       else if(identical(dp, "NULL")) dp <- character(0)
       else dp <- strsplit(dp, ",")[[1]]
       dp <- sub("[[:blank:]]*([[:alnum:]]+)", "\\1", dp) # strip whitespace
       options(defaultPackages = dp)
    })

## Expand R_LIBS_* environment variables.
Sys.setenv(R_LIBS_SITE =
           .expand_R_libs_env_var(Sys.getenv("R_LIBS_SITE")))
Sys.setenv(R_LIBS_USER =
           .expand_R_libs_env_var(Sys.getenv("R_LIBS_USER")))

local({
    if(nzchar(tl <- Sys.getenv("R_SESSION_TIME_LIMIT_CPU")))
        setSessionTimeLimit(cpu = tl)
    if(nzchar(tl <- Sys.getenv("R_SESSION_TIME_LIMIT_ELAPSED")))
        setSessionTimeLimit(elapsed = tl)
})

        setSessionTimeLimit(elapsed = tl)
})

.First.sys <- function()
{
    for(pkg in getOption("defaultPackages")) {
        res <- require(pkg, quietly = TRUE, warn.conflicts = FALSE,
                       character.only = TRUE)
        if(!res)
            warning(gettextf('package %s in options("defaultPackages") was not found', sQuote(pkg)$
                    call. = FALSE, domain = NA)
    }
}

## called at C level in the startup process prior to .First.sys
.OptRequireMethods <- function()
{
    pkg <- "methods" # done this way to avoid R CMD check warning
    if(pkg %in% getOption("defaultPackages"))
        if(!require(pkg, quietly = TRUE, warn.conflicts = FALSE,
                    character.only = TRUE))
            warning('package "methods" in options("defaultPackages") was not found',
                    call. = FALSE)
}

if(nzchar(Sys.getenv("R_BATCH"))) {
    .Last.sys <- function()
    {
        cat("> proc.time()\n")
        print(proc.time())
    }
    ## avoid passing on to spawned R processes
    ## A system has been reported without Sys.unsetenv, so try this
    try(Sys.setenv(R_BATCH=""))
}

local({
    if(nzchar(rv <- Sys.getenv("_R_RNG_VERSION_")))

local({
    if(nzchar(rv <- Sys.getenv("_R_RNG_VERSION_")))
        suppressWarnings(RNGversion(rv))
})

.sys.timezone <- NA_character_
.First <- NULL
.Last <- NULL
###-*- R -*- Unix Specific ----

.Library <- file.path(R.home(), "library")
.Library.site <- Sys.getenv("R_LIBS_SITE")
.Library.site <- if(!nzchar(.Library.site)) file.path(R.home(), "site-library") else unlist(strspl$
.Library.site <- .Library.site[file.exists(.Library.site)]

invisible(.libPaths(c(unlist(strsplit(Sys.getenv("R_LIBS"), ":")),
                      unlist(strsplit(Sys.getenv("R_LIBS_USER"), ":")
                      ))))
local({
    popath <- Sys.getenv("R_TRANSLATIONS", "")
    if(!nzchar(popath)) {
        paths <- file.path(.libPaths(), "translations", "DESCRIPTION")
        popath <- dirname(paths[file.exists(paths)][1])
    }
    bindtextdomain("R", popath)
    bindtextdomain("R-base", popath)
    assign(".popath", popath, .BaseNamespaceEnv)
})
local({
## we distinguish between R_PAPERSIZE as set by the user and by configure
papersize <- Sys.getenv("R_PAPERSIZE_USER")
if(!nchar(papersize)) {
    lcpaper <- Sys.getlocale("LC_PAPER") # might be null: OK as nchar is 0
    papersize <- if(nchar(lcpaper))
        if(length(grep("(_US|_CA)", lcpaper))) "letter" else "a4"
    else Sys.getenv("R_PAPERSIZE")
}
options(papersize = papersize,

}
options(papersize = papersize,
        printcmd = Sys.getenv("R_PRINTCMD"),
        dvipscmd = Sys.getenv("DVIPS", "dvips"),
        texi2dvi = Sys.getenv("R_TEXI2DVICMD"),
        browser = Sys.getenv("R_BROWSER"),
        pager = file.path(R.home(), "bin", "pager"),
        pdfviewer = Sys.getenv("R_PDFVIEWER"),
        useFancyQuotes = TRUE)
})

## non standard settings for the R.app GUI of the macOS port
if(.Platform$GUI == "AQUA") {
    ## this is set to let RAqua use both X11 device and X11/TclTk
    if (Sys.getenv("DISPLAY") == "")
        Sys.setenv("DISPLAY" = ":0")

    ## this is to allow gfortran compiler to work
    Sys.setenv("PATH" = paste(Sys.getenv("PATH"),":/usr/local/bin",sep = ""))
}## end "Aqua"

## de-dupe the environment on macOS (bug in Yosemite which affects things like PATH)
if (grepl("^darwin", R.version$os)) local({
    ## we have to de-dupe one at a time and re-check since the bug affects how
    ## environment modifications propagate
    while(length(dupes <- names(Sys.getenv())[table(names(Sys.getenv())) > 1])) {
        env <- dupes[1]
        value <- Sys.getenv(env)
        Sys.unsetenv(env)             ## removes the dupes, good
        .Internal(Sys.setenv(env, value)) ## wrapper requries named vector, a pain, hence internal
    }
})

local({
    tests_startup <- Sys.getenv("R_TESTS")
    if(nzchar(tests_startup)) source(tests_startup)
})

Is there anything glaring here that could be causing the issue?

Izzy
  • 53
  • 1
  • 5
  • 2
    Usually that error arises from infinite recursion, yes. Do you have some messed-up code in your `~/.Rprofile` or something? You can start R without it (and without some other things; see `R --help`) with `R --vanilla`. – alistaire Mar 28 '22 at 01:14
  • 1
    If `R --vanilla` works, and `~/.Rprofile` looks fine also check `/lib/R/etc/` for symlinks, e.g. to `/etc/R/` where user settings are stored. Try to delete or rename the `/etc/R/` directory before reinstalling R, as the files will not be overwritten. – jay.sf Mar 28 '22 at 04:52
  • @alistaire I've added my .Rprofile to the original post. Is there a way to do R --vanilla from Rstudio? It works great in terminal, but the Cstack error message is still there when I open Rstudio. – Izzy Mar 28 '22 at 15:55
  • @jay.sf, I can't find the /lib/R/etc directory through terminal. Any suggestions? Thank you! – Izzy Mar 28 '22 at 15:56
  • @Izzy probably it's slightly different on MacOS (I'm running Linux), is there perhaps a `/Users/Shared/R/` folder? – jay.sf Mar 28 '22 at 16:31
  • @jay.sf I was able to track it down using the solution posted [here](https://stackoverflow.com/questions/24880493/how-to-find-out-r-library-location-in-mac-osx). I deleted /Library/Frameworks/R.framework/Resources/etc, then uninstalled R, and re-installed R. Sadly the CStack warning is still there. – Izzy Mar 28 '22 at 16:54
  • @Izzy Could you run in terminal `find / -name Renviron.site -print 2>/dev/null` and `find / -name Rprofile.site -print 2>/dev/null` and post the location where the files are stored? – jay.sf Mar 28 '22 at 17:10
  • @jay.sf weirdly enough, both of those came up empty. However, I tried searching for .Rprofile, which produced ```/System/Volumes/Data/Users/mycomputer/.Rprofile``` and ```/Users/mycomputer/.Rprofile```. Searching for .Renviron still produced nothing. – Izzy Mar 28 '22 at 18:41
  • Ok, are both really files or one of them actually a symlink? Are both file dates from today? Is the content identical? – jay.sf Mar 28 '22 at 18:56
  • @jay.sf They are both real files as far as I can tell. Both have the same contents I added to my original post. They both appear to be from April 8, 2021. I did also find a file called "/Library/Frameworks/R.framework/Resources/library/base/R/Rprofile" and have added the contents to my post as well. – Izzy Mar 28 '22 at 19:04
  • @Izzy I would try to rename all old files. Already tried the code of `Rprofile` in a script if it produces the error? – jay.sf Mar 28 '22 at 19:11
  • When talking about an “`.Rprofile`” file, you need to be more specific: *where* is this file stored? Is it in your home directory? – Konrad Rudolph Mar 28 '22 at 19:15
  • 1
    @jay.sf I just ran the ```/Library/Frameworks/R.framework/Resources/library/base/R/Rprofile``` code and it produced the error! I'm going to try deleting it and restarting R. Wish me luck! – Izzy Mar 28 '22 at 19:16
  • @Izzy **Do NOT delete that file!** It’s part of the R installation and R will not function properly without it! – Konrad Rudolph Mar 28 '22 at 19:17
  • @KonradRudolph that is one of the issues I am trying to resolve. We have found the same file in multiple directories. – Izzy Mar 28 '22 at 19:17
  • @KonradRudolph ok I won't delete it! But do you have any suggested solutions? Can I not just delete it and re-install R? – Izzy Mar 28 '22 at 19:17
  • 1
    @Izzy Ah I see your comment further up. So, yes, it *is* in your home directory. That’s the solution then. Writing an answer … – Konrad Rudolph Mar 28 '22 at 19:18
  • 1
    @Izzy Additional note to my [comment above](https://stackoverflow.com/questions/71641315/error-c-stack-usage-is-too-close-to-the-limit-at-r-startup?noredirect=1#comment126633367_71641315): Of course another reinstall after that. – jay.sf Mar 28 '22 at 19:20
  • @Izzy Great, happy we found it finally – jay.sf Mar 28 '22 at 19:30

2 Answers2

2

Your user .Rprofile file is loading itself recursively for some reason:

if (file.exists("~/.Rprofile")) {
  base::sys.source("~/.Rprofile", envir = environment())
}

From your comments it seems that these lines are inside ~/.Rprofile (~ expands to the user home directory, i.e. /Users/mycomputer in your case, assuming mycomputer is your user name).

Delete these lines (or comment them out), they don’t belong here. In fact, the file looks like it’s a template for a project-specific .Rprofile configuration. It would make sense inside a project directory, but not as the profile-wide user .Rprofile.

The logic for these files is as follows:

  • If there is an .Rprofile file in the current directory, R attempts to load that.
  • Otherwise, if the environment variable R_PROFILE_USER is set to the path of a file, R attempts to load this file.
  • Otherwise, if the file ~/.Rprofile exists, R attempts to load that.

Now, this implies that ~/.Rprofile is not loaded automatically if a projects-specific (= in the current working directory) .Rprofile exists. This is unfortunate, therefore many projects add lines similar to the above to their project-specific .Rprofile files to cause the user-wide ~/.Rprofile to be loaded as well. However, the above implementation ignores the R_PROFILE_USER environment variable. A better implementation would therefore look as follows:

rprofile = Sys.getenv('R_PROFILE_USER', '~/.Rprofile')
if (file.exists(rprofile)) {
  base::sys.source(rprofile, envir = environment())
}
rm(rprofile)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Thank you! That is so bizarre--I have no idea how that ended up in the ```.Rprofile``` file. I ended up deleting it and re-installing R. – Izzy Mar 28 '22 at 19:29
0

Success! Thank you to everyone in the comment. The issue was resolved by deleting /Library/Frameworks/R.framework/Resources/library/base/R/Rprofile and re-installing R and Rstudio.

Izzy
  • 53
  • 1
  • 5