Intro to R programming language from Google Colab

To start with R programming language I created a small overview of what are the most important things to learn first.

How to start R on Google Colab?

It is possible to run R directly on Google Colaboratory. This means you don’t need to set the environment on your end, just to start and experiment with R.

How to get R version?

There are several ways to get the R version. All these works:

R.Version()
R.version
R.version.string
version

, but my favorite is just version.

width 80 in R

How to get built-in objects?

There is a simple builtins() command helping to return the names of all R built-in objects. These objects are fetched directly from the symbol table of the R interpreter.

builtins

I saw inside the builtins() the print function for example. This is the great intro for the next section.

How to get info about any function in R?

The key is to use the ? operator. ?print returned the description:

print prints its argument and returns it invisibly (via invisible(x)). It is a generic function which means that new printing methods can be easily added for new classes.

You can also use help(print) to get the same results.

Online information about print is also helpful.

For me the crucial thing was to use to the idea that every function in R has a package it belongs to. In case of print it is the base package.

package:base

How to show all R options?

To show all R options you simple type:

print(options())

options() allow the user to set and examine a variety of global options which affect the way in which R computes and displays its results.

To print a single option you may use getOption:

Example:

op='width'
getOption(op, default = NULL)
# same as options(op)

Output:

80

Here is how the width 80 looks:

width 80 in R

And if we alter the width option to 30 the output is different:

width 80 in R

How to plot a simple function graph in R?

For the most basic example you will need to have a seq sequence from

width 80 in R

How to get help on help in R?

It may be interesting but help(help) is also useful.

This will show the full list of help argument options:

help(topic, package=NULL, lib.loc=NULL, verbose=getOption("verbose"), try.all.packages=getOption("help.try.all.packages"), help_type=getOption("help_type"))

Also help is interesting because you can help.search() on any term which is the same as ??.

Example:

help.search('abs')
# or simple
??abs

How to get list of R available packages?

library() will list all R available packages, search() will list all loaded packages.

You can load (attach) a package with: library("dplyr'). Inside a function check if a package has been loaded with require("dplyr") that returns either TRUE or FALSE.

R packages available

Packages in library '/usr/local/lib/R/site-library':

IRdisplay               'Jupyter' Display Machinery
IRkernel                Native R Kernel for the 'Jupyter Notebook'
pbdZMQ                  Programming with Big Data -- Interface to
                        'ZeroMQ'
repr                    Serializable Representations

Packages in library '/usr/lib/R/site-library':

askpass                 Safe Password Entry for R, Git, and SSH
assertthat              Easy Pre and Post Assertions
backports               Reimplementations of Functions Introduced Since
                        R-3.0.0
base64enc               Tools for base64 encoding
BH                      Boost C++ Header Files
brew                    Templating Framework for Report Generation
broom                   Convert Statistical Analysis Objects into Tidy
                        Tibbles
callr                   Call R from R
cellranger              Translate Spreadsheet Cell Ranges to Rows and
                        Columns
cli                     Helpers for Developing Command Line Interfaces
clipr                   Read and Write from the System Clipboard
clisymbols              Unicode Symbols at the R Prompt
colorspace              A Toolbox for Manipulating and Assessing Colors
                        and Palettes
commonmark              High Performance CommonMark and Github Markdown
                        Rendering in R
covr                    Test Coverage for Packages
crayon                  Colored Terminal Output
crosstalk               Inter-Widget Interactivity for HTML Widgets
curl                    A Modern and Flexible Web Client for R
DBI                     R Database Interface
dbplyr                  A 'dplyr' Back End for Databases
desc                    Manipulate DESCRIPTION Files
devtools                Tools to Make Developing R Packages Easier
digest                  Create Compact Hash Digests of R Objects
dplyr                   A Grammar of Data Manipulation
DT                      A Wrapper of the JavaScript Library
                        'DataTables'
ellipsis                Tools for Working with ...
evaluate                Parsing and Evaluation Tools that Provide More
                        Details than the Default
fansi                   ANSI Control Sequence Aware String Functions
farver                  High Performance Colour Space Manipulation
fastmap                 Fast Implementation of a Key-Value Store
forcats                 Tools for Working with Categorical Variables
                        (Factors)
fs                      Cross-Platform File System Operations Based on
                        'libuv'
gdtools                 Utilities for Graphical Rendering
generics                Common S3 Generics not Provided by Base R
                        Methods Related to Model Fitting
ggplot2                 Create Elegant Data Visualisations Using the
                        Grammar of Graphics
gh                      'GitHub' 'API'
git2r                   Provides Access to Git Repositories
glue                    Interpreted String Literals
gtable                  Arrange 'Grobs' in Tables
haven                   Import and Export 'SPSS', 'Stata' and 'SAS'
                        Files
highr                   Syntax Highlighting for R Source Code
hms                     Pretty Time of Day
htmltools               Tools for HTML
htmlwidgets             HTML Widgets for R
httpuv                  HTTP and WebSocket Server Library
httr                    Tools for Working with URLs and HTTP
ini                     Read and Write '.ini' Files
jsonlite                A Robust, High Performance JSON Parser and
                        Generator for R
knitr                   A General-Purpose Package for Dynamic Report
                        Generation in R
labeling                Axis Labeling
later                   Utilities for Scheduling Functions to Execute
                        Later with Event Loops
lazyeval                Lazy (Non-Standard) Evaluation
lifecycle               Manage the Life Cycle of your Package Functions
lubridate               Make Dealing with Dates a Little Easier
magrittr                A Forward-Pipe Operator for R
markdown                Render Markdown with the C Library 'Sundown'
memoise                 Memoisation of Functions
mime                    Map Filenames to MIME Types
modelr                  Modelling Functions that Work with the Pipe
munsell                 Utilities for Using Munsell Colours
openssl                 Toolkit for Encryption, Signatures and
                        Certificates Based on OpenSSL
pillar                  Coloured Formatting for Columns
pkgbuild                Find Tools Needed to Build R Packages
pkgconfig               Private Configuration for 'R' Packages
pkgload                 Simulate Package Installation and Attach
plogr                   The 'plog' C++ Logging Library
plyr                    Tools for Splitting, Applying and Combining
                        Data
praise                  Praise Users
prettyunits             Pretty, Human Readable Formatting of Quantities
processx                Execute and Control System Processes
progress                Terminal Progress Bars
promises                Abstractions for Promise-Based Asynchronous
                        Programming
ps                      List, Query, Manipulate System Processes
purrr                   Functional Programming Tools
R6                      Encapsulated Classes with Reference Semantics
rcmdcheck               Run 'R CMD check' from 'R' and Capture Results
RColorBrewer            ColorBrewer Palettes
Rcpp                    Seamless R and C++ Integration
readr                   Read Rectangular Text Data
readxl                  Read Excel Files
rematch                 Match Regular Expressions with a Nicer 'API'
remotes                 R Package Installation from Remote
                        Repositories, Including 'GitHub'
reprex                  Prepare Reproducible Example Code via the
                        Clipboard
reshape2                Flexibly Reshape Data: A Reboot of the Reshape
                        Package
rex                     Friendly Regular Expressions
rlang                   Functions for Base Types and Core R and
                        'Tidyverse' Features
rmarkdown               Dynamic Documents for R
roxygen2                In-Line Documentation for R
rprojroot               Finding Files in Project Subdirectories
rstudioapi              Safely Access the RStudio API
rversions               Query 'R' Versions, Including 'r-release' and
                        'r-oldrel'
rvest                   Easily Harvest (Scrape) Web Pages
scales                  Scale Functions for Visualization
selectr                 Translate CSS Selectors to XPath Expressions
sessioninfo             R Session Information
shiny                   Web Application Framework for R
sourcetools             Tools for Reading, Tokenizing and Parsing R
                        Code
stringi                 Character String Processing Facilities
stringr                 Simple, Consistent Wrappers for Common String
                        Operations
svglite                 An 'SVG' Graphics Device
sys                     Powerful and Reliable Tools for Running System
                        Commands in R
systemfonts             System Native Font Finding
testthat                Unit Testing for R
tibble                  Simple Data Frames
tidyr                   Tidy Messy Data
tidyselect              Select from a Set of Strings
tidyverse               Easily Install and Load the 'Tidyverse'
tinytex                 Helper Functions to Install and Maintain 'TeX
                        Live', and Compile 'LaTeX' Documents
usethis                 Automate Package and Project Setup
utf8                    Unicode Text Processing
uuid                    Tools for generating and handling of UUIDs
vctrs                   Vector Helpers
viridisLite             Default Color Maps from 'matplotlib' (Lite
                        Version)
whisker                  for R, Logicless Templating
withr                   Run Code 'With' Temporarily Modified Global
                        State
xfun                    Miscellaneous Functions by 'Yihui Xie'
xml2                    Parse XML
xopen                   Open System Files, 'URLs', Anything
xtable                  Export Tables to LaTeX or HTML
yaml                    Methods to Convert R Data to YAML and Back

Packages in library '/usr/lib/R/library':

base                    The R Base Package
boot                    Bootstrap Functions (Originally by Angelo Canty
                        for S)
class                   Functions for Classification
cluster                 "Finding Groups in Data": Cluster Analysis
                        Extended Rousseeuw et al.
codetools               Code Analysis Tools for R
compiler                The R Compiler Package
datasets                The R Datasets Package
foreign                 Read Data Stored by 'Minitab', 'S', 'SAS',
                        'SPSS', 'Stata', 'Systat', 'Weka', 'dBase', ...
graphics                The R Graphics Package
grDevices               The R Graphics Devices and Support for Colours
                        and Fonts
grid                    The Grid Graphics Package
KernSmooth              Functions for Kernel Smoothing Supporting Wand
                        & Jones (1995)
lattice                 Trellis Graphics for R
MASS                    Support Functions and Datasets for Venables and
                        Ripley's MASS
Matrix                  Sparse and Dense Matrix Classes and Methods
methods                 Formal Methods and Classes
mgcv                    Mixed GAM Computation Vehicle with Automatic
                        Smoothness Estimation
nlme                    Linear and Nonlinear Mixed Effects Models
nnet                    Feed-Forward Neural Networks and Multinomial
                        Log-Linear Models
parallel                Support for Parallel computation in R
rpart                   Recursive Partitioning and Regression Trees
spatial                 Functions for Kriging and Point Pattern
                        Analysis
splines                 Regression Spline Functions and Classes
stats                   The R Stats Package
stats4                  Statistical Functions using S4 Classes
survival                Survival Analysis
tcltk                   Tcl/Tk Interface
tools                   Tools for Package Development
utils                   The R Utils Package

How to list available datasets in R?

data() will list all available datasets.

Also data loads specified datasets.

Here is the list you may expect:

Data sets in package 'datasets':

AirPassengers           Monthly Airline Passenger Numbers 1949-1960
BJsales                 Sales Data with Leading Indicator
BJsales.lead (BJsales)
                        Sales Data with Leading Indicator
BOD                     Biochemical Oxygen Demand
CO2                     Carbon Dioxide Uptake in Grass Plants
ChickWeight             Weight versus age of chicks on different diets
DNase                   Elisa assay of DNase
EuStockMarkets          Daily Closing Prices of Major European Stock
                        Indices, 1991-1998
Formaldehyde            Determination of Formaldehyde
HairEyeColor            Hair and Eye Color of Statistics Students
Harman23.cor            Harman Example 2.3
Harman74.cor            Harman Example 7.4
Indometh                Pharmacokinetics of Indomethacin
InsectSprays            Effectiveness of Insect Sprays
JohnsonJohnson          Quarterly Earnings per Johnson & Johnson Share
LakeHuron               Level of Lake Huron 1875-1972
LifeCycleSavings        Intercountry Life-Cycle Savings Data
Loblolly                Growth of Loblolly pine trees
Nile                    Flow of the River Nile
Orange                  Growth of Orange Trees
OrchardSprays           Potency of Orchard Sprays
PlantGrowth             Results from an Experiment on Plant Growth
Puromycin               Reaction Velocity of an Enzymatic Reaction
Seatbelts               Road Casualties in Great Britain 1969-84
Theoph                  Pharmacokinetics of Theophylline
Titanic                 Survival of passengers on the Titanic
ToothGrowth             The Effect of Vitamin C on Tooth Growth in
                        Guinea Pigs
UCBAdmissions           Student Admissions at UC Berkeley
UKDriverDeaths          Road Casualties in Great Britain 1969-84
UKgas                   UK Quarterly Gas Consumption
USAccDeaths             Accidental Deaths in the US 1973-1978
USArrests               Violent Crime Rates by US State
USJudgeRatings          Lawyers' Ratings of State Judges in the US
                        Superior Court
USPersonalExpenditure   Personal Expenditure Data
UScitiesD               Distances Between European Cities and Between
                        US Cities
VADeaths                Death Rates in Virginia (1940)
WWWusage                Internet Usage per Minute
WorldPhones             The World's Telephones
ability.cov             Ability and Intelligence Tests
airmiles                Passenger Miles on Commercial US Airlines,
                        1937-1960
airquality              New York Air Quality Measurements
anscombe                Anscombe's Quartet of 'Identical' Simple Linear
                        Regressions
attenu                  The Joyner-Boore Attenuation Data
attitude                The Chatterjee-Price Attitude Data
austres                 Quarterly Time Series of the Number of
                        Australian Residents
beaver1 (beavers)       Body Temperature Series of Two Beavers
beaver2 (beavers)       Body Temperature Series of Two Beavers
cars                    Speed and Stopping Distances of Cars
chickwts                Chicken Weights by Feed Type
co2                     Mauna Loa Atmospheric CO2 Concentration
crimtab                 Student's 3000 Criminals Data
discoveries             Yearly Numbers of Important Discoveries
esoph                   Smoking, Alcohol and (O)esophageal Cancer
euro                    Conversion Rates of Euro Currencies
euro.cross (euro)       Conversion Rates of Euro Currencies
eurodist                Distances Between European Cities and Between
                        US Cities
faithful                Old Faithful Geyser Data
fdeaths (UKLungDeaths)
                        Monthly Deaths from Lung Diseases in the UK
freeny                  Freeny's Revenue Data
freeny.x (freeny)       Freeny's Revenue Data
freeny.y (freeny)       Freeny's Revenue Data
infert                  Infertility after Spontaneous and Induced
                        Abortion
iris                    Edgar Anderson's Iris Data
iris3                   Edgar Anderson's Iris Data
islands                 Areas of the World's Major Landmasses
ldeaths (UKLungDeaths)
                        Monthly Deaths from Lung Diseases in the UK
lh                      Luteinizing Hormone in Blood Samples
longley                 Longley's Economic Regression Data
lynx                    Annual Canadian Lynx trappings 1821-1934
mdeaths (UKLungDeaths)
                        Monthly Deaths from Lung Diseases in the UK
morley                  Michelson Speed of Light Data
mtcars                  Motor Trend Car Road Tests
nhtemp                  Average Yearly Temperatures in New Haven
nottem                  Average Monthly Temperatures at Nottingham,
                        1920-1939
npk                     Classical N, P, K Factorial Experiment
occupationalStatus      Occupational Status of Fathers and their Sons
precip                  Annual Precipitation in US Cities
presidents              Quarterly Approval Ratings of US Presidents
pressure                Vapor Pressure of Mercury as a Function of
                        Temperature
quakes                  Locations of Earthquakes off Fiji
randu                   Random Numbers from Congruential Generator
                        RANDU
rivers                  Lengths of Major North American Rivers
rock                    Measurements on Petroleum Rock Samples
sleep                   Student's Sleep Data
stack.loss (stackloss)
                        Brownlee's Stack Loss Plant Data
stack.x (stackloss)     Brownlee's Stack Loss Plant Data
stackloss               Brownlee's Stack Loss Plant Data
state.abb (state)       US State Facts and Figures
state.area (state)      US State Facts and Figures
state.center (state)    US State Facts and Figures
state.division (state)
                        US State Facts and Figures
state.name (state)      US State Facts and Figures
state.region (state)    US State Facts and Figures
state.x77 (state)       US State Facts and Figures
sunspot.month           Monthly Sunspot Data, from 1749 to "Present"
sunspot.year            Yearly Sunspot Data, 1700-1988
sunspots                Monthly Sunspot Numbers, 1749-1983
swiss                   Swiss Fertility and Socioeconomic Indicators
                        (1888) Data
treering                Yearly Treering Data, -6000-1979
trees                   Diameter, Height and Volume for Black Cherry
                        Trees
uspop                   Populations Recorded by the US Census
volcano                 Topographic Information on Auckland's Maunga
                        Whau Volcano
warpbreaks              The Number of Breaks in Yarn during Weaving
women                   Average Heights and Weights for American Women

How to get help on any package?

Crutial in R is to get the list of all members from the package. For that case you use again the help method but you need to set the package:

Example:

help(package='base')

Output: R base package methods R base package methods The output is huge and shows all R methods from the base package.

How to get the list of all R operators?

Example:

?Syntax

This is very easy with the Syntax command from the base package. Syntax outlines R syntax and gives the precedence of operators.

The following unary and binary operators are defined.  They are
     listed in precedence groups, from highest to lowest.

       ':: :::'           access variables in a namespace              
       '$ @'              component / slot extraction                  
       '[ [['             indexing                                     
       '^'                exponentiation (right to left)               
       '- +'              unary minus and plus                         
       ':'                sequence operator                            
       '%any%'            special operators (including '%%' and '%/%') 
       '* /'              multiply, divide                             
       '+ -'              (binary) add, subtract                       
       '< > <= >= == !='  ordering and comparison                      
       '!'                negation                                     
       '&  &&'            and                                          
       '| ||'             or                                           
       '~'                as in formulae                               
       '-> ->>'           rightwards assignment                        
       '<- <<-'           assignment (right to left)                   
       '='                assignment (right to left)                   
       '?'                help (unary and binary)  

tags: intro & category: r