{"id":25176046,"url":"https://github.com/quantgen/rintro","last_synced_at":"2026-02-14T13:33:23.460Z","repository":{"id":92125018,"uuid":"101074446","full_name":"QuantGen/RIntro","owner":"QuantGen","description":null,"archived":false,"fork":false,"pushed_at":"2020-09-21T14:20:44.000Z","size":32,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-10-04T11:37:42.240Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/QuantGen.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-08-22T14:52:42.000Z","updated_at":"2020-09-21T14:20:47.000Z","dependencies_parsed_at":"2023-03-13T17:33:47.361Z","dependency_job_id":null,"html_url":"https://github.com/QuantGen/RIntro","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/QuantGen/RIntro","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/QuantGen%2FRIntro","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/QuantGen%2FRIntro/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/QuantGen%2FRIntro/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/QuantGen%2FRIntro/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/QuantGen","download_url":"https://codeload.github.com/QuantGen/RIntro/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/QuantGen%2FRIntro/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29444752,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-14T12:43:28.304Z","status":"ssl_error","status_checked_at":"2026-02-14T12:43:14.160Z","response_time":53,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-02-09T13:15:55.005Z","updated_at":"2026-02-14T13:33:23.455Z","avatar_url":"https://github.com/QuantGen.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv id=\"Outline\" /\u003e\n\n## Outline\n  * [Installation](#installation)    \n  * [Types](#types) \n  * [Basic operations with numbers](#basic-operations) \n  * [Vectors](#vectors) \n  * [Matrices](#matrices)\n  * [Data frames](#data.frames) \n  * [Reading/writing ASCII files](#read-write) \n  * [Descriptive statistics](#descriptives)\n  * [Plots](#plots) \n  * [Conditional statements](#conditionals)\n  * [Loops](#loops) \n  * [Functions](#functions) \n  * [Libraries](#libraries) \n  * [Distributions](#distributions)\n    \n-------------------------------------------------------------------------------------------\n\n\n\u003cdiv id=\"installation\" /\u003e\n\n### Installation\n\nYou can install R and R-libraries and also have access to many materials and manuals at the [R-website](https://www.r-project.org/). \n\nTo install R, follow the instructions under **Getting Started**. Once R is installed, you should have the R-icon on your programs. Click on the icon to open the R-console.\n\n[Back to Outline](#Outline)\n\n-------------------------------------------------------------------------------------------\n\n\u003cdiv id=\"types\" /\u003e\n\n### Types\n\nR support several types of variables, the basic ones are: `logical` (`TRUE`/`FALSE`), `integer`, `numeric` (double-precision, this is use for real numbers), `character` (these are used to store text), and `factors` (these are reserved for variables that can take on a limited set of values, e.g., ethnicity). The following example illustrates the creation and basic operations with this types of variables.\n\n```r\n  # numeric\n  x=1.1\n  str(x)\n  class(x)\n  \n  # integer\n  x=1\n  class(x) # by default a numeric type was created but we can coerce it to integer\n  x=as.integer(x)\n  class(x)\n  \n  # logical\n  x= 1.1 \u003e2 \n  x\n  class(x)\n  !x  # exclamation sign returns the negative of the logical value\n  isTRUE(x)\n  isTRUE(!x)\n  \n  # character\n  x='hello' # you can use either single or double quates to create a character\n  class(x)\n  print(x)\n  show(x)\n  x=\"hello\"\n```\n\n[Back to Outline](#Outline)\n\n\u003cdiv id=\"basic-operations\" /\u003e\n\n### Basic Operations with `numeric` and `integer`\n\n```r\n x=2\n x+10\n x-10\n x*4\n x^2\n sqrt(x)\n log(x) # natural log\n log(100,base=10)\n```\n[Back to Outline](#Outline)\n\n\u003cdiv id=\"vectors\" /\u003e\n\n### Vectors\n\nThe following code shows how to create vectors, subset (i.e., extract single or multiple elements) and modify (repleacement) them.\n\n```r\n  x=c(1,10,15,100)\n  x[3] # extracting one element\n  x[3]=99 # replacing one element\n  x[-3] # `-` can be used to extract all but some entries\n  \n  # Sequence\n  x=1:10 # creates a sequence from 1:10\n  x\n  x[3]=1000\n  x\n  \n  # Indexing and replacement can also be done with TRUE/FALSE\n  x=1:4\n  x[c(TRUE,FALSE,FALSE,FALSE)]\n \n  # Vectors can be of any type\n  x=c(\"a\",\"b\",\"hello\")\n  x\n  \n```\n\n[Back to Outline](#Outline)\n\n\n\u003cdiv id=\"matrices\" /\u003e\n\n### Matrices\n\nA matrix is a two dimensional array that holds values of the same type (e.g., numeric, logical). The following code illustrates how to create, subset and modify a matrix. Matrix operations will be covered in the course.\n\n\n```r\n  x1=1:10\n  x2=11:20\n  x3=21:30\n  \n  X=cbind(x1,x2,x3) # Binds columns\n  dim(X)\n  nrow(X)\n  ncol(X)\n  X\n  \n  ## Subseting \n  X[1,] # returns the first row\n  X[,2] # returns the second column\n  X[1:2,2:3] # returns the block defined by rows 1 and 2 and columns 2 and 3\n  \n  ## Replacement\n  X[2,3]=1000\n  X\n  \n  ## Try: Z=rbind(x1,x2,x3); dim(Z)\n\n \n```\n[More on Linear Algebra in R](https://github.com/gdlc/STAT_COMP/blob/master/LinearAlgebra.md)\n\n[Back to Outline](#Outline)\n\n\n\u003cdiv id=\"data.frame\" /\u003e\n\n### Data Frames\n\nVectors and matrices can store data of a single type (e.g., `numeric`, `integer`, `character`). In statistics often we need to use data tables that store variables of different types. For instance, we may want to store in a single data table: sex (\"M\"/\"F\" will be `character`, age and weight (both `numeric`). We can do this using data frames. Strictily speaking `data.frames` are `lists`; however, unlike the general list, `data.frames` are two dimensional arrays, pretty much like matrices, with the flexibility that they can store different types in the columns.\n\n[Back to Outline](#Outline)\n\n```r\n   N=100\n   x1=sample(c(\"F\",\"M\"),size=N,replace=T)\n   x2=runif(min=25,max=60,n=N) # samples 10 values from a uniform distribution with support on [25,60]\n   DATA=data.frame(sex=x1,age=x2)\n   DATA$height=ifelse(DATA$sex==\"F\",170,175)+rnorm(n=N,sd=sqrt(40)) # adding a new variable can be done this way\n   \n   head(DATA)    # prints the first rows of the data to the screen\n   tail(DATA)    # prints the last rows of the data to the screen\n   str(DATA)     # tells you the strcture (class, dimensions) of the object\n   fix(DATA)     # shows the data frame in a spread-sheet-like fashion\n   summary(DATA) # most objects in R have a summary method, note summaries depend upon the type.\n   \n   ## Indexing  \n   DATA[,1]\n   DATA$sex  # you can index by variable name, same for replacement.\n   \n   DATA[1,1]\n   DATA$sex[1]\n   \n```\n\n\u003cdiv id=\"read-write\" /\u003e\n\n### Writing/reading ASCII files\n```R\n  # Writing\n   write.table(DATA,file='DATA.txt') # writes the data to an ASCII file\n   list.files(pattern='.txt') # list the files in the current folder having *.txt in the name.\n  \n  # Reading\n   DATA2=read.table('DATA.txt',header=T) # you can add sep=\",\" or sep\"\\t\" for comma and tab-spearated files, respectively\n   head(DATA)\n   head(DATA2)\n   \n```\n[Back to Outline](#Outline)\n\n\u003cdiv id=\"descriptives\" /\u003e\n\n### Descriptive Statistics\n\n```R\n   summary(DATA$age)\n   table(DATA$sex)\n   quantile(DATA$age,p=.08)\n   isTall\u003c-ifelse(DATA$height\u003emedian(DATA$height),\"\u003emedian\",\"\u003cmedian\")\n   table(DATA$sex,isTall)\n```\n\n\u003cdiv id=\"plots\" /\u003e\n\n### Plots\n```r\n   barplot(table(DATA$sex))\n   hist(DATA$age)\n   boxplot(height~sex,data=DATA)\n   plot(height~age,data=DATA)\n   plot(density(DATA$height))\n```\n[Back to Outline](#Outline)\n\n\n\u003cdiv id=\"conditionals\" /\u003e\n\n### Conditional Statments\nIn programing conditional statements can be used to execute one type of code or another depending on a conditon.\n\n```R\n x=1\n y=2\n \n if(x\u003ey){\n   print(\"X is greater than Y!\")\n }\n \n ## IF-ELSE\n if(x\u003ey){\n   print(\"X is greater than Y!\")\n }else{\n   print(\"Y is greater than X!\")\n }\n\n ## IF-ELSE\n x=3\n if(x\u003ey){\n   print(\"X is greater than Y!\")\n }else{\n   print(\"Y is greater than X!\")\n }\n \n \n ## We can evaluate multiple conditions at a time by nesting if statments or by evaluating them jointly\n \n x=TRUE\n y=FALSE\n \n if(x){\n  if(y){\n    print(\"Both X and Y are TRUE!\")\n  }else{\n    print(\"X is TRUE and Y is FALSE\")\n  }\n }else{\n   if(y){\n    print(\"X is FALSE and Y is TRUE\")\n   }else{\n    print(\"Both X and Y are FALSE\")\n   }\n }\n\n ## Alternatively\n \n if(x\u0026y){ print(\"Both X and Y are TRUE\") }\n if(x\u0026!y){ print(\"X is TRUE and Y is FALSE\") }\n if((!x)\u0026y){ print(\"X is FALSE and Y is TRUE\") }\n if((!x)\u0026(!y)){ print(\"Both X and Y are FALSE\") }\n \n```\n[Back to Outline](#Outline)\n\n\n\u003cdiv id=\"loops\" /\u003e\n\n### Loops\n In many applications we need to repeat a task a fixed numer of times or until somthing happen. For this you can use the `for` and `while` loops.\n\n```r\n for(i in 1:10){\n   print(i)\n }\n \n ## We can iterate over any vector\n for(i in c(\"a\",\"b\",\"zzz\")){\n    print(i)\n }\n\n ## While loop\n x=0\n while(x\u003c=10){\n  x=x+1\n  print(x)\n }\n```\n[Back to Outline](#Outline)\n\n\n\u003cdiv id=\"functions\" /\u003e\n\n### Functions\nA function takes on a numbrer of arguments, carries out some computations and (often) returns an object. The `sin`, `cos` , `log` and `summary` are examples of functions that return a value.\n\n```R\n   x=100\n   sin(x)\n   cos(x)\n```\n\nYou can easily create your own functions. Remember, that in the least-squares (OLS=Ordinary Least Squares) estimate of a regression coefficient of simple linear regerssion equals the covariance between `x` and `y` divided by the variance of `x`. The following example returns OLS estimates of the intercept and regression coefficient in a simple linear regression.\n\n```R\n  myOLS=function(x,y){\n    b=cov(x,y)/var(x)\n    a=mean(y)-mean(x)*b\n    return(c(a,b))\n  }\n  \n  # simulating a simple data set\n  pred=rnorm(100)\n  response=100+.5*pred + rnorm(100)\n  \n  myOLS(x=pred,y=response)\n  \n```\n[Back to Outline](#Outline)\n\n\n\u003cdiv id=\"libraries\" /\u003e\n\n### Libraries\nThe basic installation of R comes with several functions for computation, basic statistical analyses, descriptive statistics, etc. Specialized code is contributed by develpers under the form of libraries. To use a library you first need to install it and then load it into the environment.\n\n```R\n   install.packages(pkg='BGLR', repos='https://cran.r-project.org/') # installs BGLR package from the CRAN repository.\n```\n\nNow that the package is installed you can load it into your environment.\n\n```R\n  library(BGLR)\n  \n```\n[Back to Outline](#Outline)\n\n\n\u003cdiv id=\"distributions\" /\u003e\n\n### Distributions\nPackage **stats** already included in R contains functions for *probability function*, *cumulative distribution function*, *quantile function* and *random variable generation* for many probability distributions. Functions consists of a prefix followed by the root name of the distribution.\n\n- **Probability function**. Prefix *d*\n\nCalculates the probability density function (p.d.f) for continuos distributions, *f(x)*, and the probability mass function (p.m.f) for discrete distributions, *f(x)=P(X=x)*.\n\n```R\n# For a discrete distribution (e.g.,binomial distribution)\n# Example. Suppose there are 10 multiple choice questions in an EPI class exam. Each question has 5 possible answers,\n# and only one of them is correct. The student fails the course if she/he gets fewer than 6 correct answers. \n# The probability of passing the course if the student attempts to answer every question at random is\n\ndbinom(6,10,0.2)+dbinom(7,10,0.2)+dbinom(8,10,0.2)+dbinom(9,10,0.2)+dbinom(10,10,0.2)\n\n# For a continuous distribution (e.g.,normal distribution)\n# Example. In a certain population, BMI has a normal distribution with mean=27.5 and sd=5\nx \u003c- seq(12.5,42.5,length=1000) # creates a sequence of values between 12.5 and 42.5.\ny \u003c- dnorm(x,mean=27.5, sd=5) # evaluates the density function for the values of x.\nplot(x,y,type=\"l\",main='Normal distribution with mean=27.5 and sd=5',ylab='f(x)')\n```\n\n- **Cumulative distribution**. Prefix *p*\n\nCalculates the cumulative distribution function (c.d.f.) for the random variable *X*\n\n*F(x) = P(X \u003c= x)* \n```R\n# In our EPI class example, the probability of failing the course is P(X\u003c6)=P(X\u003c=5)\npbinom(5,10,0.2)\n# Thus the probability of passing is 1-P(X\u003c=5)\n1 - pbinom(5,10,0.2)\n# or\npbinom(5,10,0.2,lower.tail=FALSE)\n\n# Normal distribution\n# In our BMI example, a person is declared obese if her/his BMI is greater or equal than 30.\n1-pnorm(30,27.5,5) # Probability that a randomly choosen person is obese\n# or\npnorm(30,27.5,5,lower.tail=FALSE)\n# Standardizing\nz \u003c- (30-27.5)/5\n1-pnorm(z) \n```\n\n*Special problem*\n\nResponse to Selection\n![](https://github.com/MarcooLopez/Miscelaneous/blob/master/RS1.png)\n\nIn a certain population of plants, the height of the plant has a Normal distribution with mean=5.3 feet and a sd=0.71.\nWe select plants that are 6.0 feet or taller to intercross to form a new generation of plants. \n\nWhis is the proportion *p*\u003csub\u003es\u003c/sub\u003e of selected individuals?\n\nWhich is the selection differential S?\n\n- **Quantile**. Prefix *q*\n\nFor continuous distributions, it calculates the inverse c.d.f. of the distribution, *x = F\u003csup\u003e-1\u003c/sup\u003e(p)* where *p = F(x)*.\n\n```R\n# Example. In testing Ho in certain experiment, we get a F-statistic=6.02 that has an F-distribution with \n# 3 and 20 d.f. in numerator and denominator, respectively. Reject Ho at a level 0.05 if 6.02 \u003e qF(0.05,3,20)\nqf(0.95,3,20) # Which is smaller than 6.02 hence rejecting Ho\n\n# Example. A sample of n=50 students was taken randomly from a heights population with unknown standard deviation.\n# The sample mean=165.4 and sample sd=8.3. Null hyphotesis Ho: Mean=163. Reject Ho at a level 0.05 if t0 \u003e qt(0.05,49)\nto=(165.4-163)/(8.3/sqrt(50)) # t-statistics\nqt(0.95,49) # 1.67 is smaller than t0=2.04 thus Ho is rejected.\n```\n\nFor discrete distribution, which have a step c.d.f an thus not invertible, the quantile is defined as the smallest value *x* such that *F(x)\u003e=p*, where *F* is the distribution function (c.d.f). \n```R\n# In our EPI class example, P(X\u003c=3)=0.879, P(X\u003c=4)=0.967 and P(X\u003c=5)=0.994, \n# so the smallest 'x' such as P(X\u003c=x)\u003e=0.9  is 4\nqbinom(0.9,10,0.2)\n```\n\n- **Random variable**. Prefix *r*\n\nSimulates random variables having a specified distribution with given parameters.\n```R\nx1 \u003c- rnorm(10000,10,2.2)   # draw 10,000 samples from a normal distribution with mean=10 and sd=2.2\nx2 \u003c- rnorm(10000,11.5,3.5)   # draw 10,000 samples from a normal distribution with mean=11.5 and sd=3.5\nplot(density(x1),ylab=\"Density\",col=\"red\")\nlines(density(x2),col=\"blue\")\nlegend(\"topright\",legend=c(\"mean=10, sd=2.2\",\"mean=11.5, sd=3.5\"),col=c(\"red\",\"blue\"),pch=20)\n```\n\n[Back to Outline](#Outline)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fquantgen%2Frintro","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fquantgen%2Frintro","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fquantgen%2Frintro/lists"}