Jump to content

R: Difference between revisions

5,170 bytes added ,  1 April
fix links
imported>Josephsdavid
(Added template default.nix and shell.nix, as well as links to non-RStudio editors)
(fix links)
 
(14 intermediate revisions by 9 users not shown)
Line 26: Line 26:
== Jupyter Notebook ==
== Jupyter Notebook ==


There is currently no package in nixpkgs to set up Jupyter Notebook with additional kernels. (Keep an eye on this [https://github.com/NixOS/nixpkgs/pull/33673 this pull request] though).
Use [https://github.com/tweag/jupyterWith jupyterWith]


For now, you can save the following into a file and run it with nix-shell:
This '''shell.nix''' file creates a jupyter environment with the IRKernel available.
<syntaxhighlight lang="nix>
<syntaxhighlight lang = "nix" >
with import <nixpkgs> {};
{ pkgs ? import <nixpkgs> {} }:                                               
let  
let                                                            
my-R-packages = with rPackages; [ ggplot2 dplyr xts ];
  jupyter = import (pkgs.fetchFromGitHub {                                    
R-with-my-packages = rWrapper.override{ packages = with rPackages; my-R-packages ++ [ JuniperKernel ]; };
    owner = "tweag";                                                          
jupyter-R-kernel = stdenv.mkDerivation {
    repo = "jupyterWith";                        
  name = "jupyter-R-kernel";
    # Replace this with current revision.                             
  buildInputs = [ pythonPackages.notebook R-with-my-packages ];
     rev = "269999caa8d506e93ff56c8643cecb91ded2fdef";                          
  unpackPhase = ":";
    sha256 = "08iig872ay8d711n2gbfzrf496m9x9a9xwr0xca9hn7j61c3xr43";          
  installPhase = ''
    fetchSubmodules = true;                                                    
     export HOME=$TMP
   }) {};                                                                      
    ${R-with-my-packages}/bin/R --slave -e "JuniperKernel::installJuniper(prefix='$out')"
                                                                               
  '';
  kernels = jupyter.kernels;                                                   
};
                                                                               
in
  irkernel = kernels.iRWith {               
mkShell rec {
      name = "nixpkgs";                                                        
  name = "jupyter-with-R-kernel";
      # Libraries to be available to the kernel.                              
  buildInputs = [ jupyter-R-kernel ];
      packages = p: with p; [                                                 
   shellHook = ''
        ggplot2                                                         
    export JUPYTER_PATH=${jupyter-R-kernel}/share/jupyter
      ];                                          
    # see https://github.com/NixOS/nixpkgs/issues/38733
     };                                                                        
    ${R-with-my-packages}/bin/R --slave -e "system2('jupyter', 'notebook')"
                                                                               
  '';
  jupyterEnvironment = (jupyter.jupyterlabWith {                               
}
      kernels = [ irkernel ];                                                  
</syntaxhighlight>
    });                                                                        
 
in                                                                             
== How does <code>rWrapper</code> work? ==
  jupyterEnvironment.env               
 
<code>rWrapper</code> simply replaces the R command in your path by a script that sets the environment variable <code>R_LIBS_SITE</code> and then runs R. [https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/r-modules/wrapper.nix]
 
== With nix-shell ==
 
Below is an example of a nix-shell build to run R with knitr for R markdown:
 
'''default.nix'''
<syntaxhighlight lang = "nix">
let
  pkgs = import <nixpkgs> {};
  stdenv = pkgs.stdenv;
in with pkgs; {
  myProject = stdenv.mkDerivation {
    name = "Speedracer";
     version = "1";
    src = if pkgs.lib.inNixShell then null else nix;
 
    buildInputs = [
      R
      rPackages.knitr
      rPackages.rmarkdown
      rPackages.knitr
    ];
  };
}
</syntaxhighlight>
</syntaxhighlight>


== R with Lorri ==
== R with Lorri ==
An example of a '''shell.nix''' for usage with [https://github.com/target/lorri lorri] is shown below:
An example of a '''shell.nix''' for usage with [https://github.com/nix-community/lorri lorri] is shown below:


<syntaxhighlight lang = "nix">
<syntaxhighlight lang = "nix">
Line 101: Line 75:
</syntaxhighlight>
</syntaxhighlight>


== R with Flakes and nix-direnv==
R and accompanying R-packages can be installed using a [[Flakes | Flake]] and then managed/activated with [https://github.com/nix-community/nix-direnv nix-direnv] to create a reproducible development environment. After the initial setup of nix-direnv (instructions provided on the GitHub README), there is a [https://github.com/nix-community/nix-direnv/blob/master/templates/flake/flake.nix flake template] provided by the nix-direnv maintainers to get started. Run <code>nix flake new -t github:nix-community/nix-direnv .</code> to initialize the flake template in your current directory. This will create a `flake.nix` file that can be edited to setup the R-environment:
<syntaxhighlight lang = "nix" >
{
  description = "A basic flake with a shell";
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
  inputs.flake-utils.url = "github:numtide/flake-utils";
  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system: let
      pkgs = nixpkgs.legacyPackages.${system};
    in {
      devShells.default = pkgs.mkShell {
        nativeBuildInputs = [ pkgs.bashInteractive ];
        buildInputs = with pkgs; [ R rPackages.pagedown chromium pandoc ];
      };
    });
}
</syntaxhighlight>
Saving the file and then running <code>direnv allow</code> in the terminal of the project directory will execute the `flake.lock` and build the shell. This will install the current version of R and the R-package {pagedown} that is in <nixpkgs>. Note additional system dependencies may need installed for certain packages to work such as pandoc for document conversion with {rmarkdown}. Here, chromium is installed in the `buildInputs` so the <code>chrome_print</code> function can be used from {pagedown}. 
[https://github.com/wbolster/emacs-direnv Emacs has support for direnv] which can be setup to use R with ESS. Direnv functionality can also be set in Doom Emacs under :tools in the `init.el` file in `.doom.d` folder.
==Install an R-package from GitHub==
The R-packages available in <nixpkgs> are generated from a recent snapshot of CRAN. You may find certain packages a version behind or want to install a package not on CRAN/Bioconducter. R-packages can be installed from GitHub using `buildRPackage` and `fetchFromGitHub`. An example of installing {rmarkdown} from GitHub using a Flake:
<syntaxhighlight lang = "nix" >
{
  description = "A basic flake with a shell";
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
  inputs.flake-utils.url = "github:numtide/flake-utils";
  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system: let
      pkgs = nixpkgs.legacyPackages.${system};
      rmark = pkgs.rPackages.buildRPackage {
        name = "rmarkdown";
        src = pkgs.fetchFromGitHub{
          owner = "rstudio";
          repo = "rmarkdown";
          rev = "b87ca50c8c4d5a5876333b598aed4eb84de925a3";
          sha256 = "12mhmmibizbxgmsns80c8h97rr7rclv9hz98zpgsl26hw3s4l0vm";
        };
  propagatedBuildInputs = with pkgs.rPackages; [bslib evaluate jsonlite knitr stringr tinytex yaml xfun];
      };
    in {
      devShells.default = pkgs.mkShell {
        nativeBuildInputs = [ pkgs.bashInteractive ];
        buildInputs = with pkgs; [ R rmark pandoc ];
      };
    });
}
</syntaxhighlight>
You will need to obtain the `rev` and `sha256` for the package on github [https://search.nixos.org/packages?channel=22.05&show=nix-prefetch-git&from=0&size=50&sort=relevance&type=packages&query=nix-prefetch-git which can be found by using the `nix-prefetch-git` command line tool.] For the above example, running <code>nix-prefetch-git https://github.com/rstudio/rmarkdown</code> from a terminal will generate the information. You may need to manually specify other R-package/system dependencies for the specific package in the `propagatedBuildInputs`. This information can be found in the `DESCRIPTION` file of the R-package source directory.
== A note on knitr ==
To knit a .Rmd file to a pdf (or .Rnw), you need to have included in your envronment <code> pkgs.texlive.combined.scheme-full</code>as well as <code> pandoc </code> or it will fail to knit. None of the other texlive packages contain the proper "frame" package. Note there are likely other workarounds but this requires the least effort.


== Other Editors ==
== Other Editors ==


'''with vim''' -  [https://nixos.wiki/wiki/Nvim-r nvim-r]
'''with vim''' -  [[Nvim-r | nvim-r]]


Note - if you are building an environment and plan on using nvim-r, it cannot also include rstudio, it will break your packages!


'''with emacs''' - [http://ess.r-project.org/ emacs speaks statistics]
'''with emacs''' - [http://ess.r-project.org/ emacs speaks statistics]
Line 112: Line 149:
== External Documentation ==
== External Documentation ==


* [https://nixos.org/nixpkgs/manual/#r-packages R user guide in nixpkgs manual]
* [https://nixos.org/manual/nixpkgs/stable/#r R user guide in nixpkgs manual]
 
== Officer package ==
 
When the R package "officer" has been installed from the Nix package manager, "save_as_docx" does not work:
 
Error in write_xml.xml_document(private$doc, file = private$filename) :
Error closing file
Calls: save_as_docx ... print.rdocx -> <Anonymous> -> write_xml -> write_xml.xml_document
In addition: Warning messages:
1: In write_xml.xml_document(private$doc, file = private$filename) :
Permission denie [1501]
2: In write_xml.xml_document(private$doc, file = private$filename) :
Permission denie [1501]
 
However officer does work if installed using the conventional install.packages() which can be enabled as discussed in
https://churchman.nl/tag/r/
 
[[Category:Languages]]