1. Home
  2. Explore
  3. Computer Science
  4. Introduction to R

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Introduction to R

Speaker 1Speaker 2

Introduction to R

20:06
0:00-20:06
  1. Anna

    Welcome to our introduction to R. R is a programming language and environment designed especially for statistics, data analysis, and data visualization. It is often described as the language of data science, and survey data from data-mining experts places R at the top of the software they use, ahead of Python, although both are major tools.

  2. Michael

    What makes R such a strong starting point? First, it is free and open source, unlike some statistical packages that can cost thousands of dollars per year. It is also optimized for vector operations, so you can often work with an entire row, column, or table without writing explicit for loops.

  3. Anna

    And R has a large, supportive community that provides examples, documentation, and continuing developments. It also has more than 9,000 contributed or third-party packages. Those packages extend R with new functions, making it possible to do nearly anything you might need to do with data.

  4. Michael

    So the basic case is this: R is important because it is widely used, free, open source, efficient with data, and supported by an enormous package ecosystem. The goal of learning it is to make your own data work more productive, interesting, and effective.

  5. Anna

    Before using R, we need to install it. Go to the R Project for Statistical Computing homepage at r-project.org, choose Download R, and then select a download mirror. The easiest option is usually the cloud mirror, because it automatically directs you to an appropriate location.

  6. Michael

    That takes you to CRAN, the Comprehensive R Archive Network. Choose your operating system there. On a Mac, download the package file and follow the standard installation instructions. On Windows, choose the base installation. Linux users can use the installation process appropriate for their distribution.

  7. Anna

    You should also download the course files from the page where the lesson is hosted. They come as a zipped folder, which you unzip to obtain R scripts with the .R extension and a folder containing data files. An R script is simply a source file containing R code.

  8. Michael

    When you open the basic R application, the source or script window is where you write programs, and the console window displays output. Lines beginning with a pound sign, or hashtag, are comments; R does not execute them. To run a line from a script, place the cursor on it and press Command-Enter on a Mac or Control-Enter on Windows.

  9. Anna

    A quick example uses the built-in datasets package and the famous iris data. After loading the package, you can inspect the first six rows with head of iris. The data contain sepal length, sepal width, petal length, petal width, and species for three kinds of iris.

  10. Michael

    You can use summary of the data to get descriptive information such as quartiles and means for quantitative variables, along with frequencies for the three species. You can also use plot on the entire dataset to get a quick visual overview. When you finish, you can detach the package and clear the console to clean up.

  11. Anna

    A more organized way to work is RStudio. RStudio is an additional application that sits on top of R; you must install R first. Go to rstudio.com, choose Download RStudio, select the desktop version, and choose the free Community edition rather than the paid version.

  12. Michael

    RStudio gives you one unified window. The source pane is usually at the top, the console is at the bottom, the environment lists variables you have created, and plots and help appear in another pane. You can resize and rearrange these areas, and keyboard shortcuts work consistently across Mac, Windows, and Linux.

  13. Anna

    That unified structure makes it easier to navigate scripts, inspect variables, view plots, and manage output. You can run the same iris examples in RStudio: load datasets, use head and summary, create a plot, clear the plots, and clear the console.

  14. Michael

    One of R's biggest strengths is its packages. A package is a bundle of code that adds functions and capabilities. Base packages are installed with R but are not necessarily loaded automatically, while contributed packages must generally be downloaded, installed, and then loaded separately.

  15. Anna

    Packages can be found through CRAN, including its task views, which organize packages by topics such as Bayesian inference or computational physics. CRANtastic lists popular and recently updated packages but redirects you to CRAN for downloads. GitHub is another source, although obtaining packages there follows a different process.

  16. Michael

    Several commonly used packages have specialized roles. dplyr helps manipulate data frames, tidyr helps clean and organize information, stringr works with text, lubridate handles dates, httr works with website data, ggplot2 creates graphics, and Shiny creates interactive web applications.

  17. Anna

    There is also rio, for importing and exporting data, and R Markdown, for creating rich documents or interactive notebooks. Pacman is a package manager that can make package installation and loading easier. For example, p_load can install a package if necessary and then load it.

  18. Michael

    Remember the difference between installing and loading. Installing puts a package on your hard drive, while loading makes it available to the current R session. You can load a package with library or require. Pacman can also load packages that are already installed, and p_unload_all can unload contributed packages. Base packages, such as datasets, are detached with R's standard detach command.

  19. Anna

    Let's move to graphics. The default plot command is a flexible starting point because it adapts to the number and type of variables you provide. With one categorical variable, such as iris dollar sign species, it creates a simple bar chart showing the three species and their counts.

  20. Michael

    With one quantitative variable, such as iris dollar sign petal dot length, plot displays the values against their row or index numbers. That can reveal the distribution and possible group differences, although the index on the horizontal axis is not especially informative.

  21. Anna

    If you give plot a categorical variable and a quantitative variable, such as species and petal length, R recognizes that combination and creates a box plot. In the iris data, the groups show strong separation on petal length.

  22. Michael

    When both variables are quantitative, such as petal length and petal width, plot creates a true scatterplot. The iris data show a strong positive association: flowers with longer petals generally also have wider petals.

  23. Anna

    Giving plot the entire iris data frame creates a matrix of scatterplots for the quantitative variables, along with displays involving species. This provides a quick holistic impression when the dataset does not contain too many variables.

  24. Michael

    You can also customize graphics. Arguments can change the color, point character, point size, title, and axis labels. For example, pch equal to 19 gives solid circles, col controls color, main supplies a title, and xlab and ylab label the axes. Even the base plot command can produce clean, informative graphics suitable for a presentation or possibly a publication.

  25. Anna

    The plot command is not limited to data frames. It can plot mathematical functions and distributions, such as a cosine curve, an exponential function, or the density of a normal distribution. Arguments such as color and line width can make those plots clearer and more presentation-ready.

  26. Michael

    For categorical data, bar charts are a simple and useful starting point. In the mtcars data, suppose we want the number of cars with four, six, or eight cylinders. Passing the raw cylinder variable directly to barplot does not produce the desired summary, because the values are listed case by case.

  27. Anna

    The solution is to create a frequency table first. The table function counts the occurrences of each cylinder value, and then barplot can display that table. In the 1974 Motor Trend car data, there are many four-cylinder cars, fewer six-cylinder cars, and a substantial number of eight-cylinder cars.

  28. Michael

    For quantitative data, the basic graphic is a histogram. Histograms help you inspect the shape of a distribution: whether it is symmetric or skewed, unimodal or bimodal, and whether it contains gaps or outliers. These features matter because unusual values and non-symmetrical distributions can affect later analyses.

  29. Anna

    Using hist on the iris variables shows different patterns. Sepal width is close to a bell-shaped distribution, while petal length and petal width have a large low-end cluster, a gap, and then another distribution. That pattern suggests that species may be producing distinct groups.

  30. Michael

    You can examine those groups with small multiples: several versions of the same graph displayed on a common scale. Set the graphical parameter to multiple rows, then create a histogram for each species using row-selection conditions. In the iris example, setosa has especially small petal measurements, while versicolor and virginica overlap but remain distinguishable.

  31. Anna

    Whenever you change graphical parameters, restore them afterward. For example, if you changed the layout to three rows and one column, return it to one row and one column when you are finished. That prevents later plots from unexpectedly using the old layout.

  32. Michael

    For two quantitative variables, use a scatterplot to examine their association. Look for linearity, consistent spread, outliers, and the strength or direction of the relationship. A fan-shaped spread indicates heteroscedasticity, which can complicate procedures that assume a more consistent spread.

  33. Anna

    In mtcars, histograms of weight and miles per gallon should be examined before plotting them together. The scatterplot shows a strong downhill pattern: heavier cars generally have lower fuel economy. You can polish the chart with solid, larger points, color, a title, and axis labels.

  34. Michael

    Plots can also be overlaid to increase information density, but restraint matters. Overlay views should complement one another rather than compete. For the lynx trapping time series, a histogram can be combined with a normal density curve, kernel density estimates, and a rug plot showing every observation.

  35. Anna

    That overlay reveals several perspectives on one distribution. The normal curve provides a comparison based on the data's mean and standard deviation. Kernel density estimates follow the observed distribution more flexibly, and changing the adjustment changes how smooth the estimate is. The rug plot marks the individual data points underneath.

  36. Michael

    After visual summaries, numerical summaries provide precision. The summary function gives category counts for categorical variables and minimum, first quartile, median, mean, third quartile, and maximum for quantitative variables. Applied to an entire data frame, it summarizes each variable in turn.

  37. Anna

    For more detail, the describe function from the psych package reports sample size, mean, standard deviation, median, trimmed mean, median absolute deviation, minimum, maximum, range, skewness, kurtosis, and standard error. It is intended for quantitative variables, so categorical variables such as iris species should not be interpreted from its numerical output.

  38. Michael

    A useful workflow is pictures first and numbers second. Histograms, box plots, and scatterplots show the structure of the data, while summary and describe give exact values that help prepare for later analyses.

  39. Anna

    R also lets you select cases. You can select rows by a category, such as cases where species equals versicolor, or by a quantitative condition, such as petal length less than two. In R, equality is written with two equals signs, and category names in quotes must match their spelling and capitalization.

  40. Michael

    You can combine conditions with an ampersand. For example, select cases where species equals virginica and petal length is less than 5.5. If you will use the same subset repeatedly, save it as a new data frame, such as a data frame containing only setosa cases. Then you can summarize or graph that smaller dataset directly.

  41. Anna

    To work effectively in R, it helps to distinguish data types from data structures. Data types include numeric values, character text, logical TRUE or FALSE values, complex numbers, and raw data. Data structures describe how those values are organized.

  42. Michael

    A vector is a one-dimensional collection whose elements all have the same data type. Even a single number is treated as a vector of length one. A matrix has rows and columns, but all of its entries must have the same class. An array extends that idea to three or more dimensions.

  43. Anna

    A data frame is a two-dimensional structure whose columns can have different types, provided the columns have the same length. It is the R structure most analogous to a spreadsheet and is commonly created when you import spreadsheet data.

  44. Michael

    A list is more flexible: its elements can have different types, lengths, and structures, and a list can contain another list. That flexibility can make lists difficult to work with. For many ordinary analyses, a data frame is a useful middle ground between simplicity and flexibility.

  45. Anna

    Coercion means changing an object from one type or structure to another. It can happen automatically or explicitly. Automatic coercion generally moves values toward the least restrictive type; if numeric, character, and logical values are combined, they may all become character values.

  46. Michael

    You can request coercion explicitly with functions such as as.integer, as.numeric, and as.data.frame. A numeric value can become an integer, character values containing numbers can become numeric, and a matrix can become a data frame. Always check the result, because automatic coercion may not be what you intended.

  47. Anna

    Factors are another important concept. A factor is an attribute of a vector that defines possible categorical values, called levels, and sometimes their order. You can convert numerical codes into factors, provide text labels such as Mac OS, Windows, and Linux, or specify an ordered sequence of levels.

  48. Michael

    Although a labeled factor may display words, it can still be stored internally as numerical codes. That is why checking the structure is useful. Factors are especially important when categorical variables need to be used in statistical analyses or experimental designs.

  49. Anna

    For small, ad hoc datasets, R provides several ways to enter values manually. The assignment operator is the less-than sign followed by a dash, read as 'gets.' Although an equal sign can work, the arrow-style operator is the conventional form, and RStudio can insert it with Option-Dash.

  50. Michael

    The colon operator creates consecutive values, such as zero through ten or ten through zero. The sequence function, written seq, gives more control, including a step size such as counting down by three. The concatenate function, written c, combines arbitrary values in whatever order you specify.

  51. Anna

    The scan function lets you enter values interactively: run scan, type a value, press Enter, and finish by pressing Enter twice. The rep function repeats values. It can repeat one value several times, repeat a set such as TRUE and FALSE in sequence, or repeat each value in a block when you use the each argument.

  52. Michael

    Most real datasets are imported rather than typed. Common formats include CSV files, which are comma-separated text files; plain text files; Excel files in XLS or XLSX format; and JSON, often used with web data.

  53. Anna

    R has built-in import functions, but the rio package provides a consistent import command that automatically recognizes many file formats. The same import function can read a CSV file, a text file, or an Excel workbook when you provide the file path.

  54. Michael

    The course examples use Google Trends data about Mozart, Beethoven, and Bach stored as CSV, TXT, and XLSX files. After importing, head shows the months and relative search popularity. RStudio's View function opens the data in a sortable spreadsheet-like viewer.

  55. Anna

    The built-in functions are still useful to recognize. read.table can import tab-delimited text, but you may need to specify header equals TRUE and the tab separator explicitly. read.csv already knows that commas separate the values. The R documentation generally recommends exporting Excel data as a tab-delimited or comma-separated file when possible, rather than importing complicated Excel workbooks directly.

  56. Michael

    Now let's turn briefly to modeling. Hierarchical clustering looks for observations that resemble one another. The result depends on the variables supplied, the distance measure, and the clustering method. Common choices include Euclidean distance, a fixed number of groups, divisive methods that split groups, and agglomerative methods that combine separate cases.

  57. Anna

    In the example, selected variables from mtcars are analyzed using Euclidean distance and hierarchical clustering. The result is plotted as a dendrogram, a tree-like display showing cases joining or splitting into groups. Cars such as the Honda Civic and Toyota Corolla appear close together, while unusual cars may separate early.

  58. Michael

    You can draw boxes around two, three, four, or five clusters to make potential groupings easier to read. But those clusters are valid only for the observations and variables you supplied. Change the variables or cases, and the clustering can change.

  59. Anna

    Principal components analysis, or PCA, is a form of dimensionality reduction. The idea is that fewer, more informative dimensions can reduce noise and make data easier to interpret. A two-dimensional analogy is projecting points onto a strong direction, then representing that direction as one principal component.

  60. Michael

    PCA begins by finding directions that capture variation in the data. Centering moves variables so their means are zero, and scaling puts them on a comparable variance scale so that one variable does not dominate simply because of its units or range.

  61. Anna

    The number of principal components equals the number of original variables, but they do not all matter equally. A summary shows the standard deviation associated with each component, and a scree plot helps identify where the important variation drops off. The rotation values describe how the original variables relate to each component.

  62. Michael

    A biplot displays the first two components. The cases appear as points or labels, while lines indicate the approximate contribution of the original variables. In the car example, the plot suggests dimensions involving large versus small cars and slow versus fast cars. Clustering grouped cases; PCA helps reveal clusters or patterns among variables and dimensions.

  63. Anna

    Regression is another major modeling approach. It uses multiple predictor variables to predict scores on one outcome variable. In the judge-rating example, several lawyer ratings are used to predict whether a judge should be retained.

  64. Michael

    In R, lm specifies a linear model. The formula places the outcome on the left of the tilde and the predictors on the right. You can enter all predictors simultaneously, or write the individual variables explicitly. The model output includes an intercept and a coefficient for each predictor.

  65. Anna

    A model summary adds standard errors, t tests, and probability values for the coefficients. It also reports multiple R-squared, which describes how well the predictors collectively account for variation in the outcome within that dataset. You can request an ANOVA table, confidence intervals, individual residuals, and a histogram of residuals.

  66. Michael

    There are many regression approaches beyond simultaneous entry. The lesson briefly demonstrates stepwise regression, stagewise regression, least-angle regression, and the lasso, or least absolute shrinkage and selection operator. Their predictive performance can be compared using R-squared, although the appropriate interpretation and limitations require more detailed study.

  67. Anna

    That brings together the main capabilities introduced here: installing R and RStudio, working with packages, exploring data visually and numerically, selecting and restructuring cases, entering and importing data, and beginning to model patterns with clustering, PCA, and regression.

  68. Michael

    For next steps, continue with more detailed R courses and practice data visualization as both a technical and a design skill. Python is another major data-science language and offers many comparable capabilities, while also serving as a general-purpose programming language.

  69. Anna

    You can also explore machine learning, which focuses on processing data and producing predictions that may generalize to other data. R users can learn through additional courses, the annual useR! conference, and local R user groups, often called RUGs.

  70. Michael

    The most important habit to carry forward is to explore your data before rushing into formal analysis. Use graphics to understand distributions and relationships, use numerical summaries for precision, choose data structures and packages thoughtfully, and remember that every model depends on the data and variables you provide.

  71. Anna

    Exactly. R gives you a flexible, open-source environment for turning data into insight. With practice, its packages, graphics, summaries, and models can make your work faster, clearer, and more effective. Happy computing.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent