R is a programming language built for statistics, data analysis, and visualization. This guide walks you through the entire workflow—from installing R and RStudio to writing your first script, importing data, making plots, and saving your work. By the end, you’ll have a reproducible R script and the confidence to explore further.
What You’ll Need
- A computer with internet access (Windows, macOS, or Linux).
- Administrator rights to install software (or permission from your IT department).
- R itself, which you download from CRAN (Comprehensive R Archive Network).
- RStudio Desktop (free version)—the integrated development environment (IDE) that makes R much easier to use.
- A CSV or Excel file to practice with (optional, but helpful).
Step-by-Step
- Install R. Go to cran.r-project.org, click “Download R for Windows” (or macOS/Linux), download the installer, and run it with default settings. On Windows, you’ll get a “R” app icon; on Mac, it’s a .pkg file.
- Install RStudio. Visit posit.co/download/rstudio-desktop/, download the free desktop version, and install it. RStudio is the interface where you’ll write and run code—it automatically finds the R installation you just added.
- Open RStudio and explore the layout. When you launch RStudio, you’ll see four panes: the Source (top-left, where you write scripts), the Console (bottom-left, where code runs), the Environment (top-right, showing your data and variables), and the Files/Plots/Help pane (bottom-right). If you don’t see all four, go to View > Panes > Show All Panes.
- Create a new R script. Click File > New File > R Script (or press
Ctrl+Shift+Non Windows/Linux,Cmd+Shift+Non Mac). A blank script opens in the Source pane. Save it immediately (Ctrl+SorCmd+S) with a name likemy_first_analysis.R. - Run your first command. In the script, type
print("Hello, R!"). Place your cursor on that line and pressCtrl+Enter(Windows/Linux) orCmd+Enter(Mac). The Console shows[1] "Hello, R!". You can also type directly into the Console and press Enter—but scripts are better for reproducibility. - Set your working directory. This tells R where to look for files and where to save outputs. In the Console, type
setwd("C:/Users/YourName/Documents/R")(adjust the path). On Mac, use something likesetwd("/Users/YourName/Documents/R"). To check, rungetwd(). Better yet, use RStudio’s Session > Set Working Directory > Choose Directory to pick a folder visually. - Import data. The easiest way is to click File > Import Dataset > From CSV (or From Excel). Choose your file, preview it, and click Import. RStudio generates the code for you and places the data in the Environment pane. Alternatively, type:
mydata <- read.csv("filename.csv")(replace with your actual file name). The<-is the assignment operator—it stores the result in a variable calledmydata. - Explore the data. Run
head(mydata)to see the first 6 rows,str(mydata)to see column types, andsummary(mydata)for basic statistics (mean, min, max, etc.). These commands are essential for understanding what you're working with. - Write a simple analysis. For example, if your data has a numeric column called
sales, runmean(mydata$sales)to get the average. The$sign accesses a column. Trytable(mydata$region)to count categories. - Create a plot. Use base R's
plot()function:plot(mydata$sales, mydata$profit)makes a scatter plot. For a histogram,hist(mydata$sales). The plot appears in the Plots pane (bottom-right). You can export it via Export > Save as Image. - Install and load packages. Packages extend R's abilities. To install the popular
dplyr(for data manipulation), runinstall.packages("dplyr")in the Console. Then load it withlibrary(dplyr). You only install once, but you must load it in every new session. - Save your work. Save your script (
Ctrl+S). To save your entire workspace (all variables), usesave.image("workspace.RData")or click the floppy disk icon in the Environment pane. To save just one object, usesaveRDS(mydata, "mydata.rds"). - Re-run everything. To run the whole script, click Source (or press
Ctrl+Shift+Son Windows,Cmd+Shift+Son Mac). This executes every line in order, giving you a reproducible analysis.
Common Mistakes
- Using
=instead of<-for assignment. While=works in most cases,<-is the R convention and avoids confusion inside function arguments. - Forgetting to load a package. If you get an error like
could not find function "%>%", you probably haven't runlibrary(dplyr)yet. - Mixing up column names. R is case-sensitive. If your column is
Sales,mydata$saleswill fail. Usenames(mydata)to check exact names. - Using the wrong working directory. If
read.csv()says “cannot open file,” the file isn't in the current working directory. Usegetwd()andsetwd()to fix it. - Overwriting existing variables. If you run
mydata <- read.csv(...)again, you replace the old data. Use different names (e.g.,data2) when experimenting.
Tips
- Use RStudio Projects. Create a project (File > New Project)—it automatically sets your working directory to the project folder, keeping everything organized.
- Comment your code. Add lines that start with
#to explain what you're doing. For example:# Calculate average sales. Future-you will thank you. - Use the help function. Type
?meanin the Console to see documentation for any function. PressF1while your cursor is on a function name to open its help page. - Learn keyboard shortcuts.
Ctrl+Enterruns the current line or selection;Ctrl+Shift+Ccomments/uncomments selected lines;Ctrl+Upbrings up command history in the Console. - Start with base R before tidyverse. Base R's
plot()andsummary()are enough for many tasks. Once comfortable, exploreggplot2for advanced graphics.
Troubleshooting
- RStudio won't open or crashes. Restart your computer, then reinstall RStudio (download the latest version). Make sure R is installed first—RStudio needs it.
- Error: “could not find function”. You likely forgot to load a package. Run
library(packageName)or check for typos in the function name. - Error: “object not found”. The variable doesn't exist. Check the Environment pane—did you run the line that creates it? Also verify spelling and case.
- Error: “cannot open file”. Your working directory is wrong or the file name is misspelled. Use
list.files()to see what files are in the current directory. - Plots not showing. In RStudio, plots appear in the Plots pane. If you're running R directly (not RStudio), a window may pop up—if not, run
dev.new()before plotting. - Package installation fails. Try
install.packages("dplyr", dependencies = TRUE). If that fails, you may need to update R (old versions can't install new packages).
Frequently Asked Questions
Q: Do I need to learn R if I already know Excel?
A: R offers more flexibility for large datasets, reproducible analysis, and advanced statistics. Excel is great for quick tasks, but R shines when you need to automate or handle millions of rows.
Q: What's the difference between R and RStudio?
A: R is the programming language (the engine). RStudio is an interface (the dashboard) that makes writing and running R code easier. You need R to use RStudio, but RStudio is optional—you could use R alone, but it's less user-friendly.
Q: How long does it take to learn R?
A: Basic proficiency (importing data, cleaning, plotting) can take a few weeks of regular practice. Mastery takes months or years, but you'll be productive quickly with focused learning.
Q: Can I use R for non-statistical tasks?
A: Yes. R can handle text processing, web scraping, and even simple automation. However, for general-purpose programming, languages like Python might be more versatile. R excels at data analysis and visualization.
Q: Why does my code work in the Console but not in a script?
A: In the Console, you run commands line by line, so you might have set a variable in a previous step. In a script, you must run the whole script or run lines in order. Use Ctrl+Enter to run each line sequentially.
Q: How do I share my R analysis with someone who doesn't have R?
A: You can export results as CSV files (write.csv(mydata, "output.csv")) or save plots as images. For interactive reports, use R Markdown to create HTML or PDF documents that include your code, output, and narrative.
Related
- Export Email to Excel: 4 Quick Ways
- Export EndNote to Excel: 4 Easy Ways
- Excel Yearly Budget Template: How to Build One
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets Named Ranges: View, Create, and ManageTo see the named range list in Google Sheets, open the spreadsheet and choose Data > Named ranges.…
- Box Plot in Excel Without Outliers: Hide or Exclude?To hide outlier markers in an Excel box plot, select the chart, right-click a data series, choose Format…
- Example Project Timeline in Excel: Build a Clear PlanTo make an example project timeline in Excel, list each task with an owner, start date, and finish…
- Online Expense Tracking Spreadsheet: How to Set It UpAn online expense tracking spreadsheet is a shared workbook that records purchases, organizes them by category, and totals…
- Excel Import CSV: Open Comma-Separated Files CorrectlyYes. To import a comma-separated CSV file in Excel for Microsoft 365 on Windows, select Data > Get…
- Delete Blank Rows in Excel Quickly: Safe Ways to CleanTo delete blank rows in Excel quickly, filter a column that every valid record must contain, select the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.