+ - * / ^
Arithmetic; ^ is evaluated first
> 2 + 3 * 3[1] 11> 2^3 / 4[1] 2
Tue Oct 27, 5:00–6:15 PM, Bunche 1209B. Bring your student ID.
Every function on Dr. Sparks’ midterm allow list, covering Chapter 1 and Sections 2.1–2.8 and 2.10. Each output on the right was produced by actually running the code in R 4.3.3, warnings and errors included, so this is exactly what R prints. Section 2.9 is not on the exam.
Calculator operators, assignment, built-in math functions and the workspace.
+ - * / ^Arithmetic; ^ is evaluated first
> 2 + 3 * 3[1] 11> 2^3 / 4[1] 2
%%Remainder after division
> 15 %% 7[1] 1
%/%Integer part of the quotient
> 15 %/% 7[1] 2
%*%Matrix multiplication
> A <- matrix(1:4, nrow = 2)> A %*% A [,1] [,2][1,] 7 15[2,] 10 22
%in%Is each element found in the other vector?
> c(1, 5) %in% 1:3[1] TRUE FALSE
<-Assign a value to a name (prints nothing)
> interest_20 <- 1.0025^20> interest_20[1] 1.051206
piBuilt-in constant; can be masked by your own object
> pi[1] 3.141593> pi <- 3> pi[1] 3> rm(pi)> pi[1] 3.141593
sqrt()Square root
> sqrt(x = 16)[1] 4
exp()e to the power x
> exp(x = 1)[1] 2.718282
log(x, base = exp(1))Logarithm; natural log by default; arguments match by name or position
> log(x = 81, base = 3)[1] 4> log(8, 2)[1] 3> log(base = 2, x = 8)[1] 3> log(8)[1] 2.079442
abs()Absolute value
> abs(c(-3, 2))[1] 3 2
floor()Largest integer not above x
> floor(c(2.7, -2.1))[1] 2 -3
factorial()x!
> factorial(4)[1] 24
ls() / objects()List objects in the workspace
> x <- 5; y <- 2> ls()[1] "x" "y"
rm()Remove objects; rm(list = ls()) clears everything
> x <- 5; y <- 2> rm(x)> ls()[1] "y"> rm(list = ls())> ls()character(0)
getwd() / setwd()Show / change the working directory
> getwd()> setwd("~/Downloads")
Not run here. Prints your folder path; setwd() changes where R looks for files.
q()Quit R
> q()Not run here. Ends the R session.
Precedence^ > unary minus > : > %% %/% > * / > + -
> -5 + 3:5 * 2[1] 1 3 5> -1:3[1] -1 0 1 2 3> -(1:3)[1] -1 -2 -3> 1:5^2 [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25> (1:5)^2[1] 1 4 9 16 25
Bad namesNames must start with a letter; R is case-sensitive
> interest_20 <- 1.05> INTEREST_20Error: object 'INTEREST_20' not found
Invalid nameNames can't start with a number
> 20_interest <- 1.0025^20Error: unexpected input in "20_"
Missing argumentArguments without a default must be supplied
> log(base = 2)Error: argument "x" is missing, with no default
Creating, sequencing, subsetting and summarizing vectors; matrices.
c()Combine; mixed modes coerce logical → numeric → character
> c(FALSE, 3, 1, TRUE)[1] 0 3 1 1> c(1, 2, "Bruins")[1] "1" "2" "Bruins"> c(TRUE, 4, "3")[1] "TRUE" "4" "3" > c(c(TRUE, 4), "3")[1] "1" "4" "3"
length()Number of elements; NA counts, NULL does not
> length(c(-3, 4/9, 2.5, 0, -1, NA))[1] 6> length(c(1, NULL, 2))[1] 2
mode()General type of the object
> mode(c(1, 2, 3))[1] "numeric"> mode(c(1, 2, "Bruins"))[1] "character"> mode(c(TRUE, FALSE))[1] "logical"
factor()Categorical vector stored as integer codes
> fac <- factor(c("group 1", "group 2", "group 2", "group 1"))> fac[1] group 1 group 2 group 2 group 1Levels: group 1 group 2> as.numeric(fac)[1] 1 2 2 1
numeric() / character() / logical()Empty vector of a given length
> numeric(3)[1] 0 0 0> character(2)[1] "" ""> logical(2)[1] FALSE FALSE
seq(from, to, by)Evenly stepped sequence; stops before passing to
> seq(from = 0, to = 10, by = 2)[1] 0 2 4 6 8 10> seq(from = 10, to = 0, by = -3)[1] 10 7 4 1
seq(..., length.out)Fixed number of evenly spaced values
> seq(from = 0, to = 1, length.out = 5)[1] 0.00 0.25 0.50 0.75 1.00> seq(from = 10, by = 5, length.out = 3)[1] 10 15 20
:Shorthand for steps of 1 or -1
> -2:2[1] -2 -1 0 1 2> 5:3[1] 5 4 3
seq_len()1, 2, ..., n (empty when n = 0)
> seq_len(4)[1] 1 2 3 4> seq_len(0)integer(0)> 1:0[1] 1 0
seq_along()Positions 1 to length(x), whatever the values are
> seq_along(c(3, 5, 7, 9))[1] 1 2 3 4> seq_along(c("friends", "waffles", "work"))[1] 1 2 3
rep(x, times)Repeat the whole vector, or each element a given number of times
> rep(c(3, 1, 4), times = 2)[1] 3 1 4 3 1 4> rep(c(1, 2), times = c(4, 3))[1] 1 1 1 1 2 2 2
rep(x, each)Repeat each element in turn
> rep(c(3, 1, 4), each = 2)[1] 3 3 1 1 4 4> rep(c(1, 2), each = 2, times = 3) [1] 1 1 2 2 1 1 2 2 1 1 2 2
sample(x, size, replace)Random draw; replace = FALSE by default (output varies)
> sample(1:6, size = 4, replace = TRUE)[1] 4 2 5 1> groups <- sample(rep(c("treatment", "control"), each = 25), size = 50, replace = FALSE)> table(groups)groups control treatment 25 25
z[x]Keep the listed positions, in that order
> z <- c("one", "two", "three", "four", "five")> z[c(3, 1)][1] "three" "one" > z[4:2][1] "four" "three" "two"
z[-x]Drop the listed positions
> z <- c("one", "two", "three", "four", "five")> z[-1][1] "two" "three" "four" "five" > z[-(1:3)][1] "four" "five"
Index edge casesZero, fraction, out of range, blank
> z <- c(10, 20, 30)> z[0]numeric(0)> z[1.9][1] 10> z[5][1] NA> z[][1] 10 20 30
Mixed signsPositive and negative indices together is an error
> x <- c(-3, 1, 2.2, 0, -1)> x[x]Error in x[x] : only 0's may be mixed with negative subscripts
z[x] <- vReplace or append elements
> obj <- c("this", "is", "content")> obj[2] <- "was"> obj[length(obj) + 1] <- "more content"> obj[1] "this" "was" "content" "more content"
Create firstYou can't create a new object with [ ]
> good <- numeric(2)> good[1:2] <- c(4, 8)> good[1] 4 8> bad[1:2] <- c(4, 8)Error: object 'bad' not found
Vector arithmeticElement by element
> c(0, 1, 2) * c(0, -1, 2)[1] 0 -1 4> (1:5) / 60[1] 0.01666667 0.03333333 0.05000000 0.06666667 0.08333333
RecyclingShorter vector repeats; warning only when lengths are not multiples
> c(1, 2) + c(4, 5, 6, 7, 8, 9)[1] 5 7 7 9 9 11> c(1, 3, 5) + c(1, 2)Warning in c(1, 3, 5) + c(1, 2) : longer object length is not a multiple of shorter object length[1] 2 5 6
matrix(data, nrow, ncol, byrow)Fills column by column unless byrow = TRUE
> matrix(1:6, nrow = 2) [,1] [,2] [,3][1,] 1 3 5[2,] 2 4 6> matrix(1:6, nrow = 2, byrow = TRUE) [,1] [,2] [,3][1,] 1 2 3[2,] 4 5 6
A[x, y]Rows x, columns y; blank means all
> A <- matrix(1:12, nrow = 3, byrow = TRUE)> A[1, 2][1] 2> A[2, ][1] 5 6 7 8> A[, 3][1] 3 7 11> A[3:2, 3][1] 11 7
sum() / prod()Total and product
> x <- c(4, 1, 3, 2)> sum(x)[1] 10> prod(x)[1] 24
mean() / median()Center
> x <- c(4, 1, 3, 2)> mean(x)[1] 2.5> median(x)[1] 2.5
var() / sd()Spread, n - 1 in the denominator
> x <- c(4, 1, 3, 2)> var(x)[1] 1.666667> sd(x)[1] 1.290994
min() / max() / range()range() returns TWO numbers, not their difference
> x <- c(4, 1, 3, 2)> min(x)[1] 1> max(x)[1] 4> range(x)[1] 1 4
IQR()Q3 - Q1
> x <- c(4, 1, 3, 2)> IQR(x)[1] 1.5
cumsum() / sort()Running total; increasing order
> x <- c(4, 1, 3, 2)> cumsum(x)[1] 4 5 8 10> sort(x)[1] 1 2 3 4
fivenum() / summary()Five-number summary; summary() adds the mean
> x <- c(4, 1, 3, 2)> fivenum(x)[1] 1.0 1.5 2.5 3.5 4.0> summary(x) Min. 1st Qu. Median Mean 3rd Qu. Max. 1.00 1.75 2.50 2.50 3.25 4.00
na.rm = TRUESummaries return NA if data contain NA, unless removed
> pm25 <- c(NA, 35, 60, 40, 20, NA, 30)> mean(pm25)[1] NA> mean(pm25, na.rm = TRUE)[1] 37
Floating-point rounding, storage types and NA / NaN / Inf / NULL.
print(x, digits)Show more digits to reveal floating-point error
> print(0.1, digits = 20)[1] 0.10000000000000000555> x_m <- c(74, 86, 91, 90, 67) / 1e3> print(x_m[2], digits = 20)[1] 0.085999999999999993117
Rounding errorMathematically equal is not always == in R
> x_mm <- c(74, 86, 91, 90, 67)> x_mm * (34/1000) / 34 == x_mm / 1e3[1] TRUE FALSE FALSE TRUE TRUE> 1.25 * (1:5 * 0.8) - 1:5[1] 0.000000e+00 0.000000e+00 4.440892e-16 0.000000e+00 0.000000e+00
OverflowToo large to store becomes Inf
> 67^10000[1] Inf> exp(1000)[1] Inf
typeof() vs mode()Integer and double are both mode numeric
> typeof(1:10)[1] "integer"> mode(1:10)[1] "numeric"> typeof(pi)[1] "double"> typeof(c(1, 2))[1] "double"
One-pass varianceUnstable when values are huge; use the two-pass form
> uhoh <- 1:10 + 1e10> n <- length(uhoh)> var(uhoh)[1] 9.166667> sum((uhoh - mean(uhoh))^2) / (n - 1)[1] 9.166667> (sum(uhoh^2) - n * mean(uhoh)^2) / (n - 1)[1] 0
NAMissing value; out-of-range index gives NA
> first_ten <- 1:10> first_ten[11][1] NA> mode(NA)[1] "logical"
NaNUndefined result
> 0 / 0[1] NaN> mean(numeric(0))[1] NaN> sqrt(-5)Warning in sqrt(-5) : NaNs produced[1] NaN
Inf / -InfInfinite limits
> 1 / 0[1] Inf> log(0)[1] -Inf
NULLNothing at all; length 0
> nada <- NULL> mode(nada)[1] "NULL"> length(nada)[1] 0> c(NULL, "test", NULL, "test test")[1] "test" "test test"
is.na() / is.nan()is.na() is TRUE for NA AND NaN
> v <- c(0, NA, NaN, Inf, -Inf)> is.na(v)[1] FALSE TRUE TRUE FALSE FALSE> is.nan(v)[1] FALSE FALSE TRUE FALSE FALSE
is.infinite() / is.finite()Finite means an ordinary number
> v <- c(0, NA, NaN, Inf, -Inf)> is.infinite(v)[1] FALSE FALSE FALSE TRUE TRUE> is.finite(v)[1] TRUE FALSE FALSE FALSE FALSE
is.null()One answer for the whole object
> is.null(c(0, NA, NaN))[1] FALSE> is.null(NULL)[1] TRUE
Counting NAsCount true NAs only, and non-missing values
> x <- c(NA, -1, 0, 1, NA, NaN, NA, Inf, NaN, NaN, 1, 10)> sum(is.na(x))[1] 6> n_NAs <- sum(is.na(x)) - sum(is.nan(x))> n_NAs[1] 3> length(x) - n_NAs[1] 9> sum(is.na(c(TRUE, FALSE, NA, NA, NaN)))[1] 3
Install once, load each session, look things up and draw quick plots.
install.packages("name")Download from CRAN once per computer
> install.packages("haven")Not run here. Downloads and installs the package. Quotes are required.
library(name)Load an installed package for this session
> library(MASS)> library(whoops)Error in library(whoops) : there is no package called ‘whoops’
search()Search path; .GlobalEnv is checked first
> search()[1] ".GlobalEnv" "package:stats" "package:graphics" [4] "package:grDevices" "package:utils" "package:datasets" [7] "package:methods" "Autoloads" "package:base"
package::objectReach a package's version directly
> pi <- 3> pi[1] 3> base::pi[1] 3.141593
? / help()Help page for a function
> ?mean> help(mean)
Not run here. Opens the documentation for mean().
?? / help.search()Fuzzy search of all help files
> ??regression> help.search("regression")
Not run here. Lists help pages that mention "regression".
hist()Histogram
> hist(islands)plot(x, y)Scatterplot
> x <- seq(1, 10)> y <- x^2 - 10 * x> plot(x, y)
curve(expr, from, to)Plot a function
> curve(expr = sin, from = 0, to = 6 * pi)Comparisons, logical indexing and Boolean operators, including how NA behaves.
< > <= >= == !=Element-wise comparisons; == compares, = assigns
> 3 < 4[1] TRUE> 7 > 7[1] FALSE> 7 >= 7[1] TRUE> 9 * 3 != 2[1] TRUE> c(1, 4, 9) == 9[1] FALSE FALSE TRUE
Recycled comparisonsShorter vector repeats, like arithmetic
> c(1, 4) == c(5, 3, 7, 4)[1] FALSE FALSE FALSE TRUE> c(1, 4, 9, 3, 8) > c(5, 6, 7)Warning in c(1, 4, 9, 3, 8) > c(5, 6, 7) : longer object length is not a multiple of shorter object length[1] FALSE FALSE TRUE FALSE TRUE
round(x, digits)Round before testing equality
> 49 * (4 / 49) == 4[1] FALSE> round(49 * (4 / 49), digits = 10) == 4[1] TRUE> round(pi, digits = 2)[1] 3.14
all.equal()Nearly equal, ignoring rounding error
> all.equal(49 * (4 / 49), 4)[1] TRUE
identical()Exactly the same, including integer vs double
> first_five <- c(1, 2, 3, 4, 5)> all(first_five == 1:5)[1] TRUE> all.equal(first_five, 1:5)[1] TRUE> identical(first_five, 1:5)[1] FALSE> identical(c(1L, 2L, 3L, 4L, 5L), 1:5)[1] TRUE
any() / all()Collapse a logical vector to one answer
> first_ten <- 1:10> any(first_ten > 7)[1] TRUE> all(first_ten > 7)[1] FALSE> any(c(NA, TRUE))[1] TRUE> all(c(NA, TRUE))[1] NA
sum() / mean() of logicalsCount of TRUE and proportion TRUE
> logi_vec <- c(TRUE, FALSE, NA)> sum(logi_vec, na.rm = TRUE)[1] 1> mean(logi_vec, na.rm = TRUE)[1] 0.5> mean(logi_vec)[1] NA
z[logical]Keep elements where the condition is TRUE; short index recycles
> num_vec <- -2:2> num_vec[num_vec > 0][1] 1 2> num_vec[num_vec %% 2 == 0][1] -2 0 2> num_vec[c(TRUE, FALSE)][1] -2 0 2
which()Positions where TRUE
> num_vec <- -2:2> which(num_vec >= 0)[1] 3 4 5> which(is.na(c(1, NA, 3, NA, Inf, NaN)))[1] 2 4 6
& | !And, or, not, element by element
> x <- c(TRUE, TRUE, FALSE, FALSE)> y <- c(TRUE, FALSE, TRUE, FALSE)> x & y[1] TRUE FALSE FALSE FALSE> x | y[1] TRUE TRUE TRUE FALSE> !x[1] FALSE FALSE TRUE TRUE
Combining conditionsRanges with & and |
> x <- -4:4> x[x < 0 | x > 0][1] -4 -3 -2 -1 1 2 3 4> x[x < 0 & x > 0]integer(0)
NA in Boolean logicNA only when the answer depends on the unknown value
> c(NA & TRUE, NA & FALSE)[1] NA FALSE> c(NA | TRUE, NA | FALSE)[1] TRUE NA> !NA[1] NA
Numbers as logicals0 is FALSE, anything else TRUE
> x <- c(-1, 0, 1, 2, NA)> y <- c(-1, 0, NA, 2, 3)> x | y[1] TRUE FALSE TRUE TRUE TRUE> x & y[1] TRUE FALSE NA TRUE NA> x[!is.na(y) & y > 0][1] 2 NA
&& / ||Single values only; stop as soon as the answer is known
> FALSE && c("Mishap 2:", "The Sequel")[1] FALSE> TRUE || c("not", "evaluated")[1] TRUE> c(TRUE, FALSE) && c(TRUE, TRUE)Error in c(TRUE, FALSE) && c(TRUE, TRUE) : 'length = 2' in coercion to 'logical(1)'
L suffixStore a number as an integer
> typeof(5)[1] "double"> typeof(5L)[1] "integer"
Run here on a small data frame written to disk and read back.
write.table(x, file)Space-separated; keeps row and column names
> parks_df <- data.frame(Name = c("Leslie", "Ron", "April"),+ Height = c(62, 71, 66), Income = c(4000, NA, 2000))> write.table(parks_df, file = "Parks.txt")> cat(readLines("Parks.txt"), sep = "\n")"Name" "Height" "Income""1" "Leslie" 62 4000"2" "Ron" 71 NA"3" "April" 66 2000
read.table(file, header, sep)Defaults: header = FALSE, sep = "" (white space)
> read.table(text = "var1 var2+ 21.2 63.2+ 44.8 94.1", header = TRUE) var1 var21 21.2 63.22 44.8 94.1> read.table(text = "var1 var2+ 21.2 63.2", header = FALSE) V1 V21 var1 var22 21.2 63.2
write.csv(x, file)Comma-separated; adds a blank-headed row-name column
> parks_df <- data.frame(Name = c("Leslie", "Ron"), Height = c(62, 71))> write.csv(parks_df, file = "Parks.csv")> cat(readLines("Parks.csv"), sep = "\n")"","Name","Height""1","Leslie",62"2","Ron",71
read.csv(file)Defaults: header = TRUE, sep = ",", fill = TRUE
> parks_df <- data.frame(Name = c("Leslie", "Ron"), Height = c(62, 71))> write.csv(parks_df, file = "Parks.csv")> read.csv("Parks.csv") X Name Height1 1 Leslie 622 2 Ron 71> read.csv("Parks.csv", row.names = 1) Name Height1 Leslie 622 Ron 71
na.stringsCodes that should become NA
> read.csv(text = "id,score+ 1,88+ 2,-9999+ 3,?", na.strings = c("-9999", "?")) id score1 1 882 2 NA3 3 NA
read.csv2() / read.delim()Semicolon (decimal comma) and tab-delimited files
> read.csv2(text = "a;b+ 1,5;2") a b1 1.5 2> read.delim(text = "a\tb\n3\t4") a b1 3 4
saveRDS() / readRDS()Save and restore one R object exactly
> x <- c(a = 1, b = 2)> saveRDS(object = x, file = "x.RDS")> readRDS(file = "x.RDS")a b 1 2
Not explicitly testedsource(), save(), save.image(), load(), read.fwf(), haven's read_spss(), read_dta(), read_sas(), read_xpt()
> library(haven)> read_dta("file.dta")
Not run here. On the allow list but not explicitly tested.
Also on the allow list.
as.numeric()Convert to numbers; unreadable text becomes NA with a warning
> as.numeric(c("41", "17"))[1] 41 17> as.numeric(c(TRUE, FALSE))[1] 1 0> as.numeric(c("4", "TRUE"))Warning: NAs introduced by coercion[1] 4 NA
as.character()Convert to text
> as.character(c(TRUE, FALSE))[1] "TRUE" "FALSE"> as.character(c(TRUE, 2))[1] "1" "2"
as.logical()Convert to TRUE / FALSE
> as.logical(c(-1, 0, 0.1, 2))[1] TRUE FALSE TRUE TRUE> as.logical(c("TRUE", "FALSE", "text", "1"))[1] TRUE FALSE NA NA
Type casting orderc() coerces before you cast
> mixed2 <- c(TRUE, FALSE, 4, "3")> mixed3 <- c(c(TRUE, FALSE, 4), "3")> mixed2[1] "TRUE" "FALSE" "4" "3" > mixed3[1] "1" "0" "4" "3"> as.numeric(mixed2)Warning: NAs introduced by coercion[1] NA NA 4 3> as.numeric(mixed3)[1] 1 0 4 3
sin() cos() tan()Trigonometry in radians
> sin(pi / 2)[1] 1> cos(pi)[1] -1> tan(pi / 4)[1] 1
asin() acos() atan()Inverse trig
> asin(1)[1] 1.570796> acos(-1)[1] 3.141593> atan(1)[1] 0.7853982
rev()Reverse order
> rev(c(3, 1, 2))[1] 2 1 3
table()Count each value
> table(c("a", "b", "a", "c", "a"))a b c 3 1 1
unique()Distinct values in first-seen order
> unique(c("Brook", "Alec", "Brook", "Diana"))[1] "Brook" "Alec" "Diana"
rowSums() / colSums()Row and column totals of a matrix
> M <- matrix(c(1, NA, 3, 4), nrow = 2)> M [,1] [,2][1,] 1 3[2,] NA 4> rowSums(M)[1] 4 NA> rowSums(M, na.rm = TRUE)[1] 4 4> colSums(M, na.rm = TRUE)[1] 1 7
names()Get or set element names
> x <- c(5, 9)> names(x) <- c("a", "b")> xa b 5 9 > names(x)[1] "a" "b"
Store each piece as a named object, then write the formula. Run here on small example data.
Variance (two-pass)Preferred; matches var()
> x <- c(1, 3, 2, 5, 6)> n <- length(x)> xbar <- mean(x)> sum((x - xbar)^2) / (n - 1)[1] 4.3> var(x)[1] 4.3
Standard deviationSquare root of the variance; one-pass form shown for comparison
> x <- c(1, 3, 2, 5, 6)> n <- length(x)> sqrt(sum((x - mean(x))^2) / (n - 1))[1] 2.073644> sqrt((sum(x^2) - n * mean(x)^2) / (n - 1))[1] 2.073644> sd(x)[1] 2.073644
Sample proportionShare of responses in a category
> alert_day <- c(TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE)> sum(alert_day) / length(alert_day)[1] 0.4285714> mean(alert_day)[1] 0.4285714
One-sample t statistict = (x̄ − μ0) / (s / √n)
> xbar <- 9.8; mu0 <- 12; s <- 6.4; n <- 320> tstat <- (xbar - mu0) / (s / sqrt(n))> tstat[1] -6.149187
Two-sample t statisticUnpaired, as in practice midterm problem 2
> x1 <- c(5.1, 4.9, 4.7, 4.6, 5.0)> x2 <- c(7.0, 6.4, 6.9, 5.5, 6.5)> (mean(x1) - mean(x2)) /+ sqrt(sd(x1)^2 / length(x1) + sd(x2)^2 / length(x2))[1] -5.685352
One-proportion z statisticz = (p̂ − p0) / √(p0(1 − p0) / n)
> x <- c(NA, -1, 0, 1, NA, NaN, NA, Inf, NaN, NaN, 1, 10)> n <- length(x)> p <- (sum(is.na(x)) - sum(is.nan(x))) / n> p0 <- 0.5> (p - p0) / sqrt(p0 * (1 - p0) / n)[1] -1.732051
Missingness by groupProportion of NAs within a subset
> pm25 <- c(NA, 35, 60, 40, 20, NA, 30)> alert_day <- c(TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE)> mean(is.na(pm25[alert_day]))[1] 0.6666667> mean(is.na(pm25[!alert_day]))[1] 0
Complete casesRows with no NA in either vector
> pm25 <- c(NA, 35, 60, 40, 20, NA, 30)> wind_speed <- c(5, 3, 4, NA, 6, 2, NA)> sum(!is.na(pm25) & !is.na(wind_speed))[1] 3
Outliers: z-scoresClass rule is |z| > 3; 2.5 here because this sample is tiny
> mpg <- c(22, 18, 25, 21, 19, 24, 20, 23, 41, NA)> z <- (mpg - mean(mpg, na.rm = TRUE)) / sd(mpg, na.rm = TRUE)> round(z, 2) [1] -0.24 -0.82 0.19 -0.39 -0.68 0.05 -0.53 -0.10 2.51 NA> which(abs(z) > 2.5)[1] 9
Outliers: 1.5 × IQRBelow Q1 − 1.5·IQR or above Q3 + 1.5·IQR
> mpg <- c(22, 18, 25, 21, 19, 24, 20, 23, 41, NA)> summary(mpg) Min. 1st Qu. Median Mean 3rd Qu. Max. NA's 18.00 20.00 22.00 23.67 24.00 41.00 1 > Q1 <- 20; Q3 <- 24; iqr <- Q3 - Q1> which(mpg < Q1 - 1.5 * iqr | mpg > Q3 + 1.5 * iqr)[1] 9> mpg[which(mpg < Q1 - 1.5 * iqr | mpg > Q3 + 1.5 * iqr)][1] 41
No functions match that filter.