Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

Statistics for Sociologists/Chapter 2: Getting Started with R and RStudio

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Chapter 2: Getting Started with R and RStudio Every statistics course eventually arrives at an awkward moment: before you can analyze anything, you have to install something. This chapter is that moment. It is not glamorous, and approximately no one has ever described installing software as "fun," but it is a one-time cost, and by the end of this chapter you will have a working statistical environment on your computer and the first few sentences of a new language under your belt. That language is R. This chapter gets you talking to it. alt=Screenshot of RStudio's interface.|center|800x800px|This is what RStudio's interface looks like. The various components will be explained below. What Is R? What Is RStudio? RR Core Team. R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. https://www.R-project.org/ is a programming language built specifically for statistics. It is free, it is open source, and it is what a very large share of working statisticians, data scientists, and quantitative social scientists actually use — not because it's trendy, but because it does what it's built to do, and thousands of people have spent decades adding to it. This is not Excel with a promotion. Excel is built for accounting, and it shows the strain the moment you ask it to do anything statistically serious. R was built for exactly this job, from the ground up. RStudio is not a different thing from R — it's a way of using R that doesn't make you want to throw your laptop out a window. R by itself is just an engine: it runs, it does the math, but it gives you almost nothing to look at while it works. RStudio is the car built around that engine — the dashboard, the windows, the seats, the place where you actually sit while the engine does its job. You will install both. You will only ever open one. Installing R and RStudio Installation instructions for software change more often than a textbook can keep up with, so rather than walk through exact button-clicking steps that may be outdated by the time you read this, here is the durable version: Go to the CRAN website (the Comprehensive R Archive Network, at cran.r-project.org) and download R for your operating system. This installs the engine. Go to Posit (posit.co, the company that makes RStudio — formerly called RStudio, in a naming decision that has confused exactly everyone) and download RStudio Desktop, the free version. This installs the dashboard. Install R first, then RStudio. Order matters here the way it matters for putting on socks before shoes. Open RStudio, not R directly. If everything installed correctly, RStudio will find R automatically and you'll never need to open R by itself again. If your first attempt at installing anything statistical software-related feels slightly wrong — like you're not sure you did it correctly even after it seems to have worked — that is a completely normal reaction and not a sign you are bad at this. Everyone in this field has had that exact feeling at least once. Most have had it more than once, usually right before an update. A Tour of RStudio When you open RStudio for the first time, you'll see it divided into several panes. Don't panic — you will not need to master all of them today. Console. The bottom-left pane (or sometimes the whole left side). This is where you type commands directly and R responds immediately. Think of it as a conversation with R that nobody saves unless you tell it to. Script Editor. The top-left pane, which appears once you open or create a script file (a plain text file ending in .R). This is where you write code you intend to keep, run, and rerun — as opposed to the Console, which forgets everything the moment you close it. Environment pane. Usually top-right. Lists every object you've created in your current session — every vector, every data frame, every variable name you've typed into existence. This is your workspace's inventory. Files / Plots / Help pane. Usually bottom-right. A multitasking corner: it shows your file browser, displays any plots you generate, and hosts R's built-in help documentation (accessible any time by typing ?functionname in the Console — a habit worth building early, since Googling "R table function" tends to return furniture before it returns documentation). The single most important habit to build right now: write your code in the Script Editor, not the Console. The Console is for quick questions you'll never need again — "what's 47 times 12" territory. Anything you might want to run again tomorrow, or hand in for an assignment, or show your professor when something breaks, belongs in a script. alt=An annotated screenshot of RStudio's interface.|border|center|800x800px|This image includes annotations so you can see the four standard RStudio panes. Basic R: Arithmetic, Assignment, and Running Code R will do arithmetic the moment you ask it to. Type this into the Console and press Enter: 2 + 2 R will respond with [1] 4. The [1] is not R being weird for its own sake — it's telling you that this is the first (and in this case only) value in the result. You'll understand why that matters once results start having more than one value, which will be almost immediately. R also does subtraction, multiplication (*), division (/), and exponents (^), in the standard order of operations. Try: (5 + 3) * 2 10 / 4 2^3 The more important operator, and the one that will confuse you for approximately one week and then never again, is assignment: <-. This stores a value under a name you choose. x <- 5 x Read <- out loud as "gets." "x gets 5" means: take the value 5, and store it in an object called x. From now on, typing x will return 5, until you assign something else to it. The arrow points in the direction the value is flowing — from the 5 into the x — which is either a small, elegant piece of interface design or the closest thing R has to a philosophical statement, depending on how much sleep you've had. Bonus: There are keyboard shortcuts to create the assignment symbol instead of having to type "<" and "-". On Linux/Windows, it is ALT + -. On Mac it is Option + -. (You can also use = for assignment in most contexts, and you will see it in other people's code. This book uses <- throughout, both because it's the R convention and because it makes the direction of "what is being stored where" unambiguous.) Objects You'll Meet: Vectors and Data Frames You don't need a full computer science vocabulary to use R, but two object types will show up constantly from Chapter 5 onward, so it's worth meeting them now, briefly, like introducing two people you'll be spending the semester with. A vector is a sequence of values of the same type — all numbers, or all text, but not mixed. You build one with the c() function (short for "combine"): ages <- c(24, 31, 45, 19, 62) ages A data frame is what you'll spend most of this book working with: a rectangular table, rows and columns, exactly like a spreadsheet, where each column is typically a vector and each row is typically a case — in this book's terms, a GSS respondent. You won't build data frames from scratch very often; you'll load them from files, starting in Chapter 3. For now, just know the shape: rows are people, columns are variables, and the whole thing is called a data frame. Packages: Teaching R New Tricks R comes with a lot built in, but the real power comes from packages — bundles of additional functions that other people have written and shared, freely, for exactly this purpose. You install a package once per computer, and load it once per R session. install.packages("tidyverse") library(tidyverse) The tidyverseWickham, H., Averick, M., Bryan, J., Chang, W., McGowan, L. D., François, R., Grolemund, G., Hayes, A., Henry, L., Hester, J., Kuhn, M., Pedersen, T. L., Miller, E., Bache, S. M., Müller, K., Ooms, J., Robinson, D., Seidel, D. P., Spinu, V., Takahashi, K., Vaughan, D., Wilke, C., Woo, K., & Yutani, H. (2019). Welcome to the tidyverse. Journal of Open Source Software, 4(43), 1686. is a collection of packages (including dplyr, which you'll use constantly, and ggplot2, which you'll meet in Chapter 7) designed to work together and, not coincidentally, designed to be more readable than base R for a lot of everyday data tasks. This is why this book teaches both base R and tidyverse/dplyr approaches side by side throughout: base R is the foundation every R user should understand, and dplyr is often the faster, more legible way to write the same operation once you know what's happening underneath it. Neither one is the "right" answer. They're two dialects of the same language, and fluent R users can generally read both even if they mostly write one. You'll want one more package now, even though you won't use it until Chapter 3: havenWickham, H., Miller, E., & Smith, D. haven: Import and Export 'SPSS', 'Stata' and 'SAS' Files. R package. https://haven.tidyverse.org, which reads data files saved in other statistical programs' native formats — including the .sav format used by SPSS, which is how you'll actually receive the GSS data for this course. install.packages("haven") library(haven) Why does a file format from a completely different program matter in an R course? Because a .sav file carries more than raw numbers — it carries the codebook's value labels and missing-value definitions baked directly into the file. Load it with the right tool, and R already knows, before you've written a single line of cleanup code, that a response of "8" means "don't know." You'll see exactly what that buys you starting in Chapter 3. When you run library(tidyverse) for the first time, R will print a small wall of text about "conflicts" and "attaching packages." This looks like an error. It is not an error. It is R being unusually polite and telling you exactly what it just did. Read it once, feel briefly reassured, and move on. Writing and Saving Scripts A script is a plain text file, saved with a .R extension, containing the code you want to keep. Build the habit now of doing your work in a script rather than typing directly into the Console: click File → New File → R Script, write your code there, and run lines or selections with Ctrl+Enter (Cmd+Return on a Mac). Save your script early and often, and save it somewhere you'll remember — ideally a dedicated folder for this course. Future you, three weeks from now, trying to remember which file had the working version of an assignment, will thank present you for this one small habit more than for almost anything else in this chapter. Setting Up an OSF Project You met the Open Science Framework conceptually in Chapter 1. Here's the practical version: go to zenodo.org, create a free account, and start a new project for this course. Give it an honest, findable name — "STATS 201 Coursework," not "final_FINAL_v3." Inside that project, you'll eventually upload the R scripts you write for each assignment. Open Science Corner #355C7D #FFFFFF #F8B195 Why bother setting this up for a class project nobody outside this course will ever see? Because the habit is the point, not the audience. Professional researchers don't reserve good data practices for the papers they expect to become famous — they build the habit early enough that it's automatic by the time it matters. You're building that habit now, on assignments with low stakes, so it's already second nature when the stakes are higher. alt=A screenshot of Zenodo.org's upload interface.|border|center|800x800px|This image show the Zenodo.org interface for uploading and managing files. A Note on R Markdown At some point — not necessarily in this course, but soon — you'll want to combine your R code, your results, and your written interpretation into a single document instead of juggling a script and a Word document separately. There are multiple tools for this, either R Markdown or Quarto, which lets you write text and code in the same file and produce a polished report (PDF, Word, or HTML) with a single click. This book won't require it, but it's worth knowing it exists: think of it as the next level once base R starts feeling comfortable, and a very good habit for anyone heading toward a senior thesis, a capstone project (see Chapter 18), or a career that involves explaining data to other humans. Base R and dplyr: Two Dialects, One Language You'll notice that starting in the next few chapters, this book routinely shows you two ways to do the same thing: a base R version and a dplyr version. This is deliberate, not redundant. Base R is the language's native grammar — it doesn't require any packages, it's what you'll find in decades of existing R codes, and understanding it makes you far less helpless when something goes wrong. dplyr, part of the tidyverse, is a more recent dialect built around a small set of readable verbs (filter(), select(), mutate(), summarize()) that often make your intentions clearer at a glance. Learning both is like learning a language's formal grammar and its everyday slang at the same time. You'll come to prefer one for most everyday work — most people eventually lean dplyr — but you'll be able to read the other one when you encounter it, which, in an R user's life, is often. Chapter Summary R is a free, powerful programming language built for statistics; RStudio is the interface that makes R usable day to day. After installing both, you'll do your work in a script (not the Console), using <- to assign values to named objects, and install.packages() plus library() to add new capabilities via packages like the tidyverse and haven. Vectors and data frames are the two object types you'll meet constantly going forward — data frames especially, since that's the shape GSS data will take starting in Chapter 3, whether you load it from a .csv file or, as this course does, a .sav file via haven. You've also set up a Zenodo.org project, established the habit of scripting your work rather than doing it by hand, and gotten a preview of R Markdown as the natural next step once this all feels less new. Every chapter from here forward will show you both base R and dplyr approaches to the same problems — two dialects of one language, both worth understanding. Practice Examples Example 1: Install, Run, Celebrate The Task: Install R and RStudio following the steps above. Open RStudio and confirm it's working. The Code: 2 + 2 The Output: [1] 4 The Interpretation: If you see [1] 4, R and RStudio are correctly installed and communicating with each other. This is a low bar, and you should clear it with a small sense of triumph anyway. Every statistical analysis in this book, no matter how sophisticated it eventually gets, rests on this exact same infrastructure working correctly. Follow-Up Challenge: Try a few more calculations of your own — including at least one using ^ for exponents and one using parentheses to control order of operations. Confirm the results match what you'd expect by hand. Example 2: Installing the Tidyverse The Task: Install and load the tidyverse package, and get comfortable with what its startup message is telling you. The Code: install.packages("tidyverse") library(tidyverse) The Output: Installation will print a fair amount of scrolling text as R downloads several packages. Loading the library will print something like: -- Attaching core tidyverse packages ------------------------ tidyverse 2.0.0 -- v dplyr 1.1.4 v readr 2.1.5 v forcats 1.0.0 v stringr 1.5.1 v ggplot2 3.5.1 v tibble 3.2.1 v lubridate 1.9.3 v tidyr 1.3.1 v purrr 1.0.2 -- Conflicts ---------------------------------------------- tidyverse_conflicts() -- x dplyr::filter() masks stats::filter() x dplyr::lag() masks stats::lag() i Use the conflicted package to force all conflicts to become errors The Interpretation: This is not an error message. It's a packing list: R is telling you exactly which packages it just loaded and which of their functions overlap with functions already built into base R (the "conflicts" section). In practice, this rarely causes problems, and you can proceed as soon as you see it. The instinct to panic at a wall of console text is one you'll want to unlearn early, because R produces a lot of informational text that looks scarier than it is. Follow-Up Challenge: Run library(tidyverse) a second time in the same session. Notice that it loads instantly with no startup message. Why do you think that is? Example 3: Your First Useful Calculation The Task: Create a vector and compute something about it — your first taste of R doing actual statistical work, however small. The Code (base R): ages <- c(24, 31, 45, 19, 62) mean(ages) The Code (dplyr equivalent, for a vector wrapped in a data frame): library(dplyr) tibble(ages = c(24, 31, 45, 19, 62)) %>% summarize(mean_age = mean(ages)) The Output: [1] 36.2 The Interpretation: The average of these five ages is 36.2 years. This is, admittedly, not a sociological finding of great consequence — but it is the same operation, structurally, that you'll be performing on thousands of real GSS respondents by Chapter 8. The mechanics don't change; only the size and meaningfulness of the data does. Follow-Up Challenge: Add a sixth age to the vector and recompute the mean by hand before running the code again. Does R's answer match yours? If your data represented real respondents, what else would you want to know about this group before drawing any conclusions from a single average? References