МатематикаМоя статистика
Тест по языку R
100 вопросов в 11 темах (лёгкий — 35, средний — 40, сложный — 25). Выберите темы, уровень и количество вопросов — к каждому ответу есть объяснение.
Векторы и recycling, типы и NA, индексация, списки и data frame, функции, apply, строки, распределения, модели lm/glm, tidyverse и типичные ловушки. Вопросы на английском.
Все вопросы теста 100
Нажмите на вариант ответа, чтобы проверить себя, или «Показать ответ».
Vectors and recycling9
What does this code print?
x <- c(1, 2, 3)
x * 2- [1] 1 2 3 1 2 3
- [1] 12
- Error: non-conformable arguments
- [1] 2 4 6
Arithmetic in R is vectorized: the scalar 2 is recycled to length 3 and each element is multiplied, giving 2 4 6. Repeating the vector is what
rep(x, 2) does, and 12 would be sum(x) * 2 — no loop or sum is implied by *.What does this code print?
x <- 1:10
sum(x > 5)- [1] 40
- [1] 6
- Error: cannot sum a logical vector
- [1] 5
x > 5 is a logical vector with five TRUE values (6..10). sum() coerces TRUE to 1 and FALSE to 0, so it counts them: 5. 40 is the sum of the values 6..10 themselves — that would be sum(x[x > 5]).What happens when this code runs?
c(1, 2, 3) + c(10, 20)- It stops with an error because the lengths 3 and 2 differ
- It prints [1] 11 22 3 with no warning
- It prints [1] 11 22 13 with a warning that the longer length is not a multiple of the shorter one
- It prints [1] 11 22 with no warning
R still recycles c(10, 20) as 10 20 10, giving 11 22 13, but because 3 is not a multiple of 2 it adds the warning "longer object length is not a multiple of shorter object length". It is a warning, not an error, and R neither pads with 0 nor truncates to the shorter length.
What does this code print?
x <- 1:6
x[c(TRUE, FALSE)]- [1] 1
- [1] 1 3 5
- [1] 2 4 6
- [1] 1 2
A logical index is recycled to the length of x: TRUE FALSE TRUE FALSE TRUE FALSE, which keeps elements 1, 3 and 5. Expecting just 1 forgets recycling; c(TRUE, FALSE) is not the same as the numeric index c(1, 0) or 1:2.
What is the first row of the result?
m <- matrix(1:6, nrow = 2)
m + c(10, 20)- 11 23 15
- 11 12 13
- Error: non-conformable arrays
- 11 13 15
matrix() fills column by column, so row 1 is 1 3 5 and row 2 is 2 4 6. The vector c(10, 20) is recycled in the same column-major order (10 20 10 20 10 20), so every row-1 element gets 10: 11 13 15. 11 23 15 assumes recycling along rows, and 11 12 13 assumes the matrix was filled by row.
What does this code print?
c(1, 2, 3, 4) + c(10, 20)- [1] 11 22 3 4
- [1] 11 22 13 24 and a warning about lengths
- [1] 11 22 13 24
- Error: vectors must have the same length
The shorter vector is recycled: c(10, 20) becomes 10 20 10 20, so the result is 11 22 13 24. R does not pad with zeros, and since 4 is a multiple of 2 there is no warning at all.
What does this code print?
seq(2, 11, by = 3)- [1] 2 5 8
- [1] 2 5 8 11
- [1] 2 5 8 11 14
- [1] 2 3 4 5 6 7 8 9 10 11
seq() starts at 2 and adds 3 while it does not exceed 11: 2, 5, 8, 11. The end point is included when it is hit exactly; it never overshoots to 14. A step of 1 is the default only when
by is not given.What is the result of this code?
x <- 1:5
x[8] <- 8L
x- The vector grows to length 8; positions 6 and 7 become NA
- Error: subscript out of bounds
- The vector grows to length 8; positions 6 and 7 become 0
- x stays 1 2 3 4 5 and a warning is issued
Assigning beyond the end of an atomic vector extends it, and the gap is filled with NA: 1 2 3 4 5 NA NA 8. "subscript out of bounds" is what you get when *reading*
[[ past the end of a list, and R never fills gaps with 0.What does this code print?
x <- c(5, 2, 9, 1)
order(x)- [1] 4 2 1 3
- [1] 1 2 5 9
- [1] 3 2 4 1
- [1] 3 1 2 4
order() returns the indices that would sort x: the smallest value 1 is at position 4, then 2 at position 2, 5 at 1, 9 at 3. 1 2 5 9 is sort(x), 3 2 4 1 is rank(x) (the rank of each element), and 3 1 2 4 is the decreasing order.Data types and coercion9
What does this code print?
typeof(5)- [1] "integer"
- [1] "numeric"
- [1] "number"
- [1] "double"
A plain number literal is stored as a double; you need the L suffix (5L) for an integer. "numeric" is what
class(5) or mode(5) reports, not typeof(), and "number" is not an R type at all.What does this code print?
c(length(NULL), length(NA))- [1] 0 0
- [1] 1 1
- [1] 0 1
- [1] NA NA
NULL is the empty object — it has length 0. NA is a missing *value*: a logical vector of length 1 containing one missing element. Treating NA as "nothing" (length 0) is the typical confusion between NA and NULL.
What does this code print?
f <- factor(c("low", "high", "medium", "low"))
levels(f)- [1] "low" "high" "medium"
- [1] "low" "medium" "high"
- [1] "low" "high" "medium" "low"
- [1] "high" "low" "medium"
By default factor() sorts the unique values to build the levels, so they come out alphabetically: high, low, medium. Neither order of appearance nor the "natural" low < medium < high order is used — pass
levels = c("low", "medium", "high") for that. Levels are unique, so "low" cannot repeat.What does this code print?
c(NA & FALSE, NA | TRUE, NA & TRUE)- [1] NA NA NA
- [1] FALSE TRUE TRUE
- [1] FALSE FALSE NA
- [1] FALSE TRUE NA
R uses three-valued logic: if the result is the same whatever NA stands for, it is returned. FALSE & anything is FALSE, TRUE | anything is TRUE. Only NA & TRUE truly depends on the unknown value, so it stays NA. Expecting NA everywhere is the "NA poisons everything" overgeneralization.
What does this code print?
class(c(1, "a", TRUE))- [1] "numeric"
- [1] "logical"
- [1] "character"
- [1] "list"
An atomic vector holds a single type, so c() coerces everything to the most flexible one: logical < integer < double < character. Here 1 and TRUE become "1" and "TRUE". A mix of types does not create a list — only
list() does that.What is the result of as.numeric("abc")?
- An error: cannot coerce "abc" to numeric
- NA, with the warning "NAs introduced by coercion"
- 0
- NaN
Failed conversions do not stop the program: the element becomes NA and R emits a warning. NaN is reserved for undefined arithmetic like 0/0, and R never silently turns text into 0.
What does this code print?
c(is.na(NaN), is.nan(NA))- [1] FALSE FALSE
- [1] TRUE TRUE
- [1] FALSE TRUE
- [1] TRUE FALSE
is.na() returns TRUE for both NA and NaN, because NaN also counts as missing. is.nan() is stricter: it is TRUE only for NaN, so is.nan(NA) is FALSE. Assuming the two functions are symmetric gives TRUE TRUE.What does this code print?
x <- c(1, NA, 3)
x == NA- [1] FALSE TRUE FALSE
- [1] FALSE FALSE FALSE
- [1] NA NA NA
- Error: comparison with NA is not allowed
Any comparison with NA is itself unknown, so every element gives NA — even the NA position. The test you wanted is
is.na(x), which gives FALSE TRUE FALSE.What does this code print?
as.logical(c("yes", "TRUE", "T", "0"))- [1] TRUE TRUE TRUE FALSE
- [1] NA TRUE NA FALSE
- [1] NA TRUE NA NA
- [1] NA TRUE TRUE NA
For strings, as.logical() only recognizes "T", "TRUE", "true", "True" (and the F/false counterparts); anything else, including "yes" and "0", becomes NA. The string "0" is not the number 0 —
as.logical(0) would be FALSE, but text is not parsed as a number first.Indexing and subsetting9
What does this code print?
x <- c(10, 20, 30, 40)
x[-2]- [1] 30
- [1] 10 20 30
- [1] 10 30 40
- [1] 40
A negative index *drops* elements: x[-2] is x without its second element. It does not count from the end as in Python, so it is neither 30 (second from the end) nor 40.
What does this code print?
x <- c("a", "b", "c")
x[0]- [1] "a"
- [1] NA
- character(0)
- Error: index 0 is out of range
R indices start at 1. Index 0 selects nothing, so the result is an empty character vector, printed as character(0). Expecting "a" is the 0-based-language habit; NA is what you get for an index past the end, like x[4].
What does this code print?
df <- data.frame(x = 1:3, y = c("a", "b", "c"))
df[df$x > 1, "y"]- [1] "b" "c"
- [1] "a"
- [1] 2 3
- [1] "a" "b" "c"
The row index
df$x > 1 is FALSE TRUE TRUE, selecting rows 2 and 3, and the column index "y" picks that column. Since one column is selected, the result is dropped to a plain character vector "b" "c". 2 3 is the x values of those rows, not y.What does this code return?
m <- matrix(1:6, nrow = 2)
dim(m[1, ])- [1] 1 3
- [1] 3 1
- NULL
- [1] 3
Selecting a single row drops the unused dimension (
drop = TRUE by default), so m[1, ] is a plain vector 1 3 5, and a plain vector has no dim attribute — dim() returns NULL. To keep a 1×3 matrix write m[1, , drop = FALSE]. 3 would be length(m[1, ]).What does this code print?
l <- list(value = 5)
c(is.null(l$val), is.null(l[["val"]]))- [1] FALSE TRUE
- [1] TRUE TRUE
- [1] FALSE FALSE
- [1] TRUE FALSE
$ on a list does partial matching: "val" uniquely matches "value", so l$val returns 5 (not NULL). [[ uses exact matching by default (exact = TRUE), so l[["val"]] finds nothing and returns NULL. This silent partial matching is why [[ is preferred in code.What does this code print?
x <- c(a = 1, b = 2, c = 3)
x[c("c", "a")]- The values 1 and 3, labelled a and c (original order)
- The values 3 and 1 without names
- The values 3 and 1, labelled c and a (in that order)
- Error: character subscripts are not allowed
Named vectors can be indexed by name, and the result keeps both the requested order and the names: c = 3, then a = 1. The order of the index wins over the original order, and names are not stripped by
[.What does this code print?
l <- list(a = 1, b = "x")
c(class(l["a"]), class(l[["a"]]))- [1] "numeric" "numeric"
- [1] "list" "list"
- [1] "list" "numeric"
- [1] "numeric" "list"
Single brackets on a list always return a (sub)list — the train with fewer carriages. Double brackets extract the element itself — the contents of the carriage — here the number 1. Treating
[ and [[ as interchangeable is one of the most common R mistakes.What happens here?
x <- 1:5
x[c(-1, 2)]- [1] 2
- An error: only 0 may be mixed with negative subscripts
- [1] 2 3 4 5 2
- [1] 2 3 4 5
An index vector must be either all non-negative or all non-positive. Mixing -1 with 2 is ambiguous ("drop 1" and "take 2" at the same time), so R stops with "only 0's may be mixed with negative subscripts". It does not silently apply both operations.
What does this code print?
x <- c(1, NA, 3)
x[x > 1]- [1] 3
- [1] NA 3
- [1] 1 3
- Error: missing value where TRUE/FALSE needed
x > 1 is FALSE NA TRUE. An NA in a logical index selects "an unknown element", which comes back as NA, so the result is NA 3. To keep only real matches use x[which(x > 1)] or x[!is.na(x) & x > 1]. The error message belongs to if(), not to indexing.Lists and data frames9
What does this code print?
l <- list(a = 1, b = 2, c = 3)
l$b <- NULL
names(l)- [1] "a" "b" "c"
- NULL
- [1] "a" "c" "b"
- [1] "a" "c"
Assigning NULL to a list element with
$<- (or [[<-) removes that element, so only "a" and "c" remain. It does not store a NULL value in place, and it does not move b to the end.What does this code print?
x <- unlist(list(a = 1, b = list(c = 2, d = 3)))
names(x)- [1] "a" "c" "d"
- [1] "a" "b.c" "b.d"
- [1] "a" "b"
- NULL
unlist() flattens nested lists into one vector and builds names by joining the outer and inner names with a dot: a, b.c, b.d. The outer name "b" is not discarded, and the names are not lost entirely (that needs use.names = FALSE).In R 4.0 or later, what does this code print?
df <- data.frame(g = c("a", "b"))
class(df$g)- [1] "character"
- [1] "factor"
- [1] "list"
- [1] "data.frame"
Since R 4.0.0 the default is
stringsAsFactors = FALSE, so strings stay character vectors. Expecting "factor" comes from older R versions and older tutorials. $ extracts the column itself, so the class is not "data.frame" or "list".What does this code print?
l <- list(a = 1, b = 2)
l["b"] <- list(NULL)
length(l)- [1] 2
- [1] 1
- [1] 0
- Error: replacement has length zero
With single brackets and
list(NULL) on the right, R stores a NULL *value* in element b instead of deleting it, so the list still has 2 elements (l$b is NULL). Deletion happens with l$b <- NULL or l[["b"]] <- NULL. This is the standard way to put a NULL inside a list.What does this code print?
df <- data.frame(a = 1:3, b = c("x", "y", "z"))
dim(df)- [1] 2 3
- [1] 6
- [1] 3
- [1] 3 2
dim() returns rows then columns: 3 rows, 2 columns. 2 3 swaps the order, 6 is the number of cells, and 3 is just nrow(df).What does this code print?
df <- data.frame(x = 1:5, y = 6:10, z = 11:15)
length(df)- [1] 5
- [1] 15
- [1] 3
- [1] 1
A data frame is a list of equal-length columns, so
length() returns the number of columns (list elements): 3. 5 is nrow(df) and 15 is the number of cells — the typical mistake is to expect the number of rows.What happens when this code runs?
df <- data.frame(x = 1:3, y = 1:2)- A 3-row data frame where y is recycled to 1 2 1
- An error: arguments imply differing number of rows: 3, 2
- A 3-row data frame where the last y is NA
- A 2-row data frame (x is truncated)
data.frame() only recycles a column when its length divides the number of rows evenly (e.g. 1:2 into 4 rows). 2 does not divide 3, so it stops with an error instead of recycling with a warning like vector arithmetic does. It never pads with NA or truncates.
What does this code print?
df <- data.frame(a = 1:3, b = 4:6)
c(class(df[, 2]), class(df[2, ]))- [1] "data.frame" "data.frame"
- [1] "integer" "integer"
- [1] "data.frame" "integer"
- [1] "integer" "data.frame"
Selecting one column with
[ , j] drops to the column vector (an integer vector here), but selecting one row with [i, ] keeps a data frame, because a row can mix types of different columns. Expecting the same behaviour for rows and columns is the trap.What does this code print?
a <- data.frame(id = c(1, 2, 3), x = c("p", "q", "r"))
b <- data.frame(id = c(2, 3, 4), y = c(TRUE, FALSE, TRUE))
c(nrow(merge(a, b)), nrow(merge(a, b, all = TRUE)))- [1] 3 4
- [1] 2 6
- [1] 2 4
- [1] 3 3
merge() joins on the common column
id. By default it is an inner join, keeping only ids present in both (2 and 3): 2 rows. all = TRUE makes a full outer join with ids 1, 2, 3, 4 (missing cells become NA): 4 rows. 3 would be a left join (all.x = TRUE), and 6 would be stacking the frames.Functions and scoping9
What does f(3) return?
f <- function(x, y = 2) x^y
f(3)- [1] 6
- [1] 9
- [1] 8
- Error: argument "y" is missing
y was not supplied, so its default 2 is used: 3^2 = 9. 6 is 3 * 2 (confusing ^ with *) and 8 is 2^3 (arguments swapped). A default value prevents the "missing argument" error.
What does the last line print?
x <- 1
f <- function() {
x <- 2
invisible(x)
}
f()
x- [1] 2
- NULL
- Error: object x is locked
- [1] 1
<- inside a function creates a local variable in the function's own environment; the global x is untouched and still 1. Changing a global from inside would need <<- (or assign()), which is rarely a good idea.What does this call return?
f <- function(a, b) a * 2
f(3, stop("boom"))- Error: boom
- [1] 6
- Error: unused argument
- [1] NA
Arguments are evaluated lazily — only when the function body uses them. f never touches b, so the
stop("boom") promise is never forced and the call returns 6. Expecting an error assumes arguments are evaluated before the call, as in most other languages.What does this call return?
f <- function(value, verbose = FALSE) value
f(val = 3)- Error: unused argument (val = 3)
- Error: argument "value" is missing, with no default
- [1] 3
- [1] FALSE
R matches arguments in three passes: exact names, then *partial* (prefix) names, then position. "val" is a unique prefix of "value", so it binds to value and the call returns 3. Partial matching is legal but considered bad style because it silently breaks when a new argument with the same prefix is added.
What does the last line print?
make_counter <- function() {
i <- 0
function() {
i <<- i + 1
i
}
}
c1 <- make_counter()
c1()
c1()
c2 <- make_counter()
c(c2(), c1())- [1] 1 3
- [1] 3 4
- [1] 1 1
- [1] 3 3
Each call of make_counter() creates a fresh environment with its own i, and the returned closure keeps it alive.
<<- updates i in that enclosing environment. c1 has been called twice, so its next call gives 3; c2 is brand new, so its first call gives 1. Counters do not share state, and they are not reset between calls.What does f(5) return?
f <- function(x) {
x + 1
x * 2
}
f(5)- [1] 10
- [1] 6
- [1] 6 10
- NULL
Without an explicit return(), a function returns the value of the last evaluated expression, x * 2 = 10. The value of x + 1 is computed and thrown away; it is not returned or combined with the later result.
What does g() return?
x <- 10
f <- function() x
g <- function() {
x <- 20
f()
}
g()- [1] 20
- Error: object x not found
- NULL
- [1] 10
R uses lexical scoping: a free variable is looked up where the function was *defined*, not where it is *called*. f was defined in the global environment, so it sees the global x = 10, not g's local x = 20. Answering 20 assumes dynamic scoping.
What does this call return?
f <- function(...) length(list(...))
f(1, "a", NULL)- [1] 3
- [1] 2
- [1] 1
- Error: NULL is not allowed in ...
... collects all extra arguments, and list() keeps a NULL as an element, so there are 3. The answer 2 comes from thinking of c(1, "a", NULL), where c() drops NULL. 1 would mean all arguments were packed into one element, which list(...) does not do.What does f(1) return?
f <- function(x, y = x * 2) {
x <- 100
y
}
f(1)- [1] 2
- [1] 100
- [1] 200
- Error: object x not found
Default arguments are lazy promises evaluated inside the function's environment the first time they are used. y is first used after x has been reassigned to 100, so y = 100 * 2 = 200. Answering 2 assumes defaults are computed at call time, like Python.
Control flow and apply family9
What does this code print?
sapply(1:3, function(i) i^2)- [1] 1 4 9
- [1] 2 4 6
- [[1]]
[1] 1
[[2]]
[1] 4
[[3]]
[1] 9 - [1] 14
sapply() applies the function to each element and simplifies the results to a vector: 1 4 9. The list output is what lapply() returns, 2 4 6 would be i * 2, and 14 is the sum of the squares.
What does this code print?
res <- 0
for (i in 1:5) {
if (i %% 2 == 0) next
res <- res + i
}
res- [1] 9
- [1] 6
- [1] 15
- [1] 1
next skips to the next iteration, so even i are skipped and res = 1 + 3 + 5 = 9. 6 is the sum of the even numbers, 15 ignores the skip, and 1 is what break instead of next would give.What does this code print?
mapply(function(x, y) x + y, 1:3, 4:6)- [1] 5 7 9
- [1] 21
- [1] 5 6 7 6 7 8 7 8 9
- Error: FUN must take one argument
mapply() walks over several vectors in parallel, calling the function with the first elements, then the second ones, and so on: 1+4, 2+5, 3+6. It is not an outer product of all combinations (9 values), and it does not sum everything.
What happens when this code runs?
vapply(1:3, function(i) i * 2, character(1))- It returns "2" "4" "6"
- It returns 2 4 6
- An error: values must be type 'character', but the result is type 'double'
- It returns a list of three numbers
vapply() takes a template (FUN.VALUE) of the expected type and length and checks every result against it. Here the function returns doubles while the template is character(1), so vapply stops instead of converting. This strictness is exactly why vapply is safer than sapply in functions.
What does this code print?
ifelse(c(1, 5, 10) > 4, "big", "small")- [1] "big"
- [1] "small"
- Error: the condition has length > 1
- [1] "small" "big" "big"
ifelse() is the vectorized conditional: it tests every element and picks from "big"/"small" element by element. A single result would come from
if, and the length error is what if (not ifelse) gives for a vector condition.What does this code print?
class(lapply(1:2, function(i) i * 10))- [1] "list"
- [1] "numeric"
- [1] "integer"
- [1] "matrix" "array"
lapply() always returns a list, one element per input, no matter what the function returns. Simplification to a vector or matrix is what sapply()/vapply() do.
In R 4.2 or later, what happens here?
if (c(TRUE, FALSE)) "yes"- It returns "yes", using only the first element
- It returns "yes" twice
- It returns NULL
- An error: the condition has length > 1
if needs a single TRUE/FALSE. Older R used the first element with a warning; since R 4.2.0 a condition of length > 1 is an error. For element-wise choices use ifelse(); for "any"/"all" semantics wrap the condition in any() or all().What does this code print?
dim(sapply(1:3, function(i) c(i, i^2)))- [1] 3 2
- NULL
- [1] 2 3
- [1] 6
Each call returns a length-2 vector, so sapply() simplifies the results into a matrix with one *column* per input element: 2 rows × 3 columns. Expecting 3 × 2 assumes one row per input (that would be
t() of the result). NULL would be a plain vector.What does this code print?
switch("b", a = 1, b = , c = 3)- NULL
- [1] 1
- [1] 3
- Error: empty alternative in switch
In switch(), an empty alternative falls through to the next non-empty one, so "b" shares the value of c: 3. Returning NULL (invisibly) is what happens when nothing matches at all, which is not the case here.
Strings and regex9
What does this code print?
c(paste("a", "b"), paste0("a", "b"))- [1] "ab" "ab"
- [1] "a b" "a b"
- [1] "a b" "ab"
- [1] "ab" "a b"
paste() joins with sep = " " by default; paste0() is paste() with sep = "". Forgetting the default space of paste() is a common source of unexpected "a b" values.
What does this code print?
sprintf("%.2f", 2/3)- [1] "0.67"
- [1] "0.66"
- [1] 0.67
- [1] "0.666666666666667"
"%.2f" formats a number with two decimals, rounding (not truncating) 0.6667 to "0.67". sprintf() always returns a character string, so the result is quoted, not the number 0.67.
What does this code print?
paste(c("x", "y"), 1:2, sep = "_", collapse = "+")- [1] "x_1" "y_2"
- [1] "x+1_y+2"
- [1] "x_y_1_2"
- [1] "x_1+y_2"
paste() first combines the vectors element-wise using sep ("x_1", "y_2"), then collapse glues the resulting vector into a single string with "+". Without collapse the result would be the two strings "x_1" "y_2"; swapping the roles of sep and collapse gives "x+1_y+2".
What does this code print?
grepl("^R", c("R lang", "lang R", "r"))- [1] TRUE TRUE TRUE
- [1] TRUE FALSE FALSE
- [1] TRUE TRUE FALSE
- [1] 1
^ anchors the pattern at the start of the string, so only "R lang" matches; "lang R" has R at the end, and "r" fails because regex matching is case-sensitive by default (use ignore.case = TRUE). grepl() returns a logical per element; the index 1 is what grep() would return.
What does this code print?
s <- "a1b22c333"
regmatches(s, gregexpr("[0-9]+", s))[[1]]- [1] "1"
- [1] "122333"
- [1] "1" "22" "333"
- [1] 1 22 333
gregexpr() finds *all* matches of one or more digits, and regmatches() extracts them as strings: "1", "22", "333". regexpr() (without the g) would find only the first one, "1". The matches are character strings, not numbers.
What does this code print?
c(nchar("hello"), length("hello"))- [1] 5 5
- [1] 1 1
- [1] 1 5
- [1] 5 1
nchar() counts characters inside each string: 5. length() counts elements of the vector, and "hello" is a character vector with one element. Using length() to measure a string's length is a classic slip for people coming from other languages.
What does this code print?
strsplit("a,b,c", ",")[[1]][2]- [1] "a"
- [1] "b"
- [1] ","
- Error: subscript out of bounds
strsplit() returns a list (one element per input string), so
[[1]] takes the character vector "a" "b" "c" and [2] picks "b". Forgetting the [[1]] is the usual mistake — then [2] would ask for a second list element, which does not exist.What does this code print?
c(sub("a", "o", "banana"), gsub("a", "o", "banana"))- [1] "bonono" "bonono"
- [1] "bonana" "bonana"
- [1] "bonana" "bonono"
- [1] "banano" "bonono"
sub() replaces only the first match, gsub() ("global") replaces every match. "banano" assumes sub() starts from the end.
What does this code print?
gsub(".", "-", "a.b")- [1] "---"
- [1] "a-b"
- [1] "a.b"
- [1] "-.b"
The pattern is a regular expression, and "." means "any character", so every character is replaced: "---". To replace a literal dot use
fixed = TRUE or escape it as "\\." in R source — then the result is "a-b".Statistics and distributions9
What does this code print?
x <- c(1, NA, 3)
c(mean(x), mean(x, na.rm = TRUE))- [1] 2 2
- [1] NA 2
- [1] 1.333333 2
- Error: missing values in x
By default an NA makes the mean unknown, so mean(x) is NA. With na.rm = TRUE the NA is removed first: (1 + 3) / 2 = 2. 1.333333 would treat the NA as 0 and still divide by 3 — R never does that.
What does rnorm(100, 5) generate?
- 100 values from a normal distribution with mean 0 and standard deviation 5
- 100 values from a normal distribution with mean 5 and standard deviation 1
- 5 values with mean 100
- 100 values with mean 5 and variance 5
The signature is rnorm(n, mean = 0, sd = 1), so the second positional argument is the mean and sd keeps its default 1. Thinking the second argument is the spread (sd or variance) is a common misreading — name your arguments to avoid it.
For Z ~ N(0, 1), which call returns P(Z > 2)?
- dnorm(2)
- qnorm(2)
- pnorm(2, lower.tail = FALSE)
- 1 - dnorm(2)
pnorm() is the CDF, P(Z ≤ z);
lower.tail = FALSE (or 1 - pnorm(2)) gives the upper tail, about 0.0228. dnorm() is the density height at 2, not a probability, and qnorm() expects a probability, so qnorm(2) is NaN with a warning.With R's default quantile type, what does this print?
quantile(1:10, 0.25)- 3 (labelled 25%)
- 3.25 (labelled 25%)
- 2.75 (labelled 25%)
- 2.5 (labelled 25%)
The default type 7 places the p-quantile at position 1 + (n − 1)·p = 1 + 9 × 0.25 = 3.25 in the sorted data, interpolating between 3 and 4: 3.25. Textbook definitions often differ — 2.75 is type 6 (position p(n + 1)), and 3 or 2.5 come from "median of the lower half"-style rules. Always check
type when comparing with other software.What does this code print?
x <- c(2, 4, 9)
c(mean(x), median(x))- [1] 4 5
- [1] 5 4
- [1] 5 5
- [1] 15 4
The mean is (2 + 4 + 9) / 3 = 5, the median is the middle value of the sorted data, 4. Note how the large value 9 pulls the mean above the median. 15 is the sum, not the mean.
What does this code print?
set.seed(42); a <- runif(3)
set.seed(42); b <- runif(3)
identical(a, b)- [1] TRUE
- [1] FALSE
- It depends on the computer clock
- Error: seed already set
set.seed() puts the random number generator into a fixed state, so the same calls after the same seed produce exactly the same "random" numbers. This is what makes simulations and analyses reproducible.
Approximately what does qnorm(0.975) return?
- 0.835
- 0.975
- 1.96
- 2.58
qnorm() is the quantile function (inverse CDF) of the standard normal: the z with P(Z ≤ z) = 0.975 is about 1.959964, the familiar 1.96 of 95% confidence intervals. About 0.835 is pnorm(0.975), i.e. treating the probability as a z value; 2.58 is qnorm(0.995).
What does sd() return here (rounded)?
sd(c(2, 4, 4, 4, 5, 5, 7, 9))- 2.138
- 2
- 4
- 4.571
The mean is 5 and the squared deviations sum to 32. sd() is the *sample* standard deviation, dividing by n - 1 = 7: √(32/7) ≈ 2.138. 2 is the population sd (dividing by n = 8), and 4 and 4.571 are the corresponding variances.
What is pbinom(2, size = 5, prob = 0.5)?
- 0.5
- 0.3125
- 0.8125
- 0.1875
pbinom() is the CDF: P(X ≤ 2) = (C(5,0) + C(5,1) + C(5,2)) / 32 = (1 + 5 + 10) / 32 = 0.5. 0.3125 = 10/32 is dbinom(2, 5, 0.5), the probability of exactly 2; 0.8125 is P(X ≤ 3) and 0.1875 is P(X ≤ 1).
Models9
In lm(y ~ x1 + x2, data = d), which variable is the response (dependent variable)?
- x1
- x2
- x1 and x2 together
- y
In R formula syntax the response is on the left of the tilde and the predictors are on the right.
+ adds predictors to the model; it does not create a combined response.Which formula fits a regression of y on x without an intercept?
- y ~ x - 1
- y ~ x + 1
- y ~ x + 0 + 1
- y ~ I(x - 1)
The intercept is included implicitly;
- 1 (or + 0) removes it. + 1 just states the default intercept explicitly, and I(x - 1) subtracts 1 from the x values arithmetically — the model still has an intercept.What does the last line return?
d <- data.frame(x = 1:5, y = c(3, 5, 7, 9, 11))
fit <- lm(y ~ x, data = d)
predict(fit, newdata = data.frame(x = 10))- 11
- 21 (named "1")
- The 5 fitted values for the original data
- 10
The data lie exactly on y = 1 + 2x, so the prediction at x = 10 is 21 (predict() names it by the row of newdata, "1"). The column in newdata must have the same name as the predictor — here it does, so the original fitted values are not returned. 11 is the last observed y.
Why is I() needed in lm(y ~ x + I(x^2))?
- I() marks x^2 as an integer variable
- I() makes the term independent of x so they are not collinear
- Inside a formula ^ means crossing of terms, so x^2 alone would just be x; I() makes it arithmetic squaring
- It is not needed: y ~ x + x^2 fits the same quadratic model
Formula operators (+, *, :, ^, -) have special meanings.
(a + b)^2 means all terms up to second-order interactions, so x^2 collapses to just x and the quadratic term silently disappears. I() ("as is") protects the expression so it is evaluated arithmetically. poly(x, 2) is an alternative.fit <- glm(y ~ x, family = binomial, data = d). What does predict(fit, newdata = nd) return by default?
- Predicted probabilities between 0 and 1
- Predicted log-odds (the linear predictor)
- Predicted classes 0 or 1
- Predicted odds
For glm, predict() defaults to type = "link", i.e. the linear predictor on the logit scale. You need
type = "response" to get probabilities. Thresholding into 0/1 classes is never done by predict() — you do it yourself, e.g. with ifelse(p > 0.5, 1, 0).What are the fitted coefficients?
x <- 1:5
y <- 2 * x + 1
coef(lm(y ~ x))- Intercept 2, slope 1
- Intercept 0, slope 2
- Only a slope of about 2.27 (no intercept)
- Intercept 1, slope 2
The data lie exactly on y = 1 + 2x, so least squares recovers intercept 1 and slope 2. lm() includes an intercept by default, so the slope is not forced through the origin (that would need
y ~ x - 1 or y ~ 0 + x).The formula y ~ a * b is equivalent to which formula?
- y ~ a:b
- y ~ a + b + a:b
- y ~ I(a * b)
- y ~ a + b
In formulas
* means "main effects plus interaction", so a * b expands to a + b + a:b. a:b alone is only the interaction term, I(a * b) is the arithmetic product used as one predictor, and a + b has no interaction.fit <- lm(y ~ x, data = d). Which expression returns the model's R²?
- fit$r.squared
- summary(fit)$r.squared
- coef(fit)["r.squared"]
- anova(fit)$R2
R² is computed by summary.lm(), so it is in
summary(fit)$r.squared (and $adj.r.squared for adjusted R²). The lm object itself has no r.squared component — fit$r.squared silently returns NULL — and coef() holds only the coefficients.g is a factor with levels "a", "b", "c". What coefficient names does coef(lm(y ~ g)) have?
- "ga" "gb" "gc"
- "(Intercept)" "gb" "gc"
- "(Intercept)" "ga" "gb" "gc"
- "(Intercept)" "g"
With treatment contrasts (the default), the first level "a" is the reference absorbed into the intercept, and each other level gets a dummy coefficient: gb and gc measure differences from level a. Including ga as well would make the design matrix collinear with the intercept. A factor is never fitted as a single numeric slope "g".
Packages and the tidyverse9
Which dplyr verb chooses columns (variables) rather than rows?
- filter()
- select()
- arrange()
- summarise()
select() keeps or drops columns. filter() keeps rows that satisfy a condition, arrange() reorders rows and summarise() collapses rows into summaries. Mixing up select() and filter() is the most common beginner slip.
In ggplot2, how are layers combined into one plot?
- With the pipe |>, e.g. ggplot(d, aes(x, y)) |> geom_point()
- With +, e.g. ggplot(d, aes(x, y)) + geom_point()
- By passing them as a list to print()
- With %>%, e.g. ggplot(d, aes(x, y)) %>% geom_point()
ggplot2 builds a plot by adding components with
+. Using a pipe passes the plot as the first argument (data) of geom_point(), which fails. This is a frequent error when mixing dplyr pipelines with ggplot code.What does this code print?
library(dplyr)
tibble(x = 1:3) |>
mutate(y = x * 2, z = y + 1) |>
pull(z)- [1] 3 5 7
- [1] 2 3 4
- Error: object 'y' not found
- [1] 2 4 6
Inside mutate() new columns are created in order, so z can use y defined in the same call: y = 2 4 6, z = 3 5 7. pull() extracts the column as a vector. Expecting an error assumes all expressions are evaluated at once, as in base transform().
What happens in this plot?
ggplot(d, aes(x, y, color = "blue")) +
geom_point()- All points are blue and there is no legend
- Points get ggplot2's first default hue (reddish) and a legend shows the label "blue"
- An error: "blue" is not a column of d
- The points are invisible
Inside aes() values are *mapped*: "blue" is treated as a constant data value, so ggplot creates a one-level color scale with the default palette (a salmon-red) and a legend entry "blue". To *set* a fixed color, put it outside aes():
geom_point(color = "blue").The dplyr package is already installed. Which line makes its functions available in the current session?
- install.packages("dplyr")
- library(dplyr)
- source("dplyr")
- import dplyr
install.packages() downloads and installs a package once; library() attaches an installed package each session. source() runs an R script file, and
import is Python syntax.What does this code print (R 4.1 or later)?
c(1, 4, 9) |> sqrt() |> sum()- [1] 6
- [1] 3.741657
- [1] 1 2 3
- [1] 14
The native pipe passes the left side as the first argument of the next call: sum(sqrt(c(1, 4, 9))) = 1 + 2 + 3 = 6. 3.741657 is sqrt(sum(...)), the wrong order of operations, and 14 is the sum without the square root.
How many rows does the result have?
library(dplyr)
mtcars |>
group_by(cyl) |>
summarise(n = n())- 32
- 1
- 11
- 3
mtcars has 32 cars with 4, 6 or 8 cylinders. group_by() + summarise() returns one row per group, so 3 rows. 32 is the number of input rows (that is what mutate() would keep), 1 would be summarise() without grouping, and 11 is the number of columns of mtcars.
How many rows does the result have?
library(dplyr)
tibble(x = c(1, NA, 3)) |>
filter(x > 1) |>
nrow()- 1
- 2
- 3
- Error: missing values in filter()
filter() keeps rows where the condition is TRUE and drops both FALSE and NA.
NA > 1 is NA, so that row is dropped, and only x = 3 remains. Base df[df$x > 1, ] would instead return an extra all-NA row — a real difference between base R and dplyr.Which line correctly passes a data frame d into the data argument of lm() using the native pipe (R 4.2+)?
- d |> lm(y ~ x)
- d |> lm(y ~ x, data = .)
- d |> lm(y ~ x, _)
- d |> lm(y ~ x, data = _)
The native pipe inserts the left side as the *first* argument, which for lm() is the formula, so
d |> lm(y ~ x) breaks. The placeholder _ (R 4.2+) must be used with a named argument, so data = _ works while a bare positional _ is a syntax error. . is the magrittr %>% placeholder and is not special for |>.Gotchas10
What does this code print?
0.1 + 0.2 == 0.3- [1] TRUE
- [1] NA
- [1] FALSE
- Error: cannot compare doubles
0.1, 0.2 and 0.3 are not exactly representable in binary floating point, and 0.1 + 0.2 is 0.30000000000000004. Compare doubles with a tolerance:
isTRUE(all.equal(0.1 + 0.2, 0.3)) is TRUE.x is an empty vector. How many times does this loop print?
x <- c()
for (i in 1:length(x)) print(i)- Never
- Once: it prints 0
- It stops with an error
- Twice: it prints 1 and then 0
length(x) is 0, and 1:0 is the *decreasing* sequence 1 0, so the loop runs twice — usually followed by index errors in real code. Use
seq_along(x) or seq_len(length(x)), which give an empty sequence and zero iterations.What does this code print?
T <- FALSE
if (T) "yes" else "no"- [1] "yes"
- Error: cannot change value of locked binding for T
- Error: invalid argument
- [1] "no"
T and F are ordinary variables that merely default to TRUE and FALSE, so they can be overwritten; TRUE and FALSE are reserved words that cannot. After
T <- FALSE the condition is FALSE. Always write TRUE/FALSE in full in real code.What does this code return?
max(numeric(0))- -Inf, with a warning
- NA
- 0
- NULL
max() of an empty set is defined as -Inf (the identity element for max, so max(c(x, y)) == max(max(x), max(y)) always holds), and R warns "no non-missing arguments to max; returning -Inf". Code that takes the max of a filtered vector can get -Inf silently propagated if it ignores the warning.
What does this code print?
seq(0, 1, by = 0.1)[4] == 0.3- [1] FALSE
- [1] TRUE
- [1] NA
- Error: subscript out of bounds
seq() computes its elements as from + i * by, so the 4th element is 3 * 0.1 = 0.30000000000000004, while the literal 0.3 is the nearest double to 0.3, a slightly different number. The printed values look identical, but == compares exact bits. Use all.equal() or round() for such comparisons.
What does this code print?
identical(1L, 1)- [1] TRUE
- [1] FALSE
- [1] NA
- Error: different types
1L is an integer and 1 is a double; identical() also compares types, so they are not identical.
1L == 1 is TRUE, because == coerces both to double first. Forgetting that plain numbers are doubles in R causes surprises with identical() and typeof().What does this code print?
x <- numeric(0)
length(seq_along(x))- [1] 0
- [1] 1
- [1] 2
- Error: x is empty
seq_along(x) returns 1, 2, ..., length(x), and for an empty vector that is integer(0), with length 0. That is why
for (i in seq_along(x)) safely does nothing on empty input, unlike 1:length(x), which would give 1 0.What does this code print?
-2^2- [1] -4
- [1] 4
- [1] NaN
- Error: unexpected ^
^ binds tighter than unary minus, so -2^2 is -(2^2) = -4, as in mathematical notation. To square negative two write (-2)^2, which is 4.
What does this code print?
f <- factor(c("10", "20", "10"))
as.numeric(f)- [1] 10 20 10
- [1] NA NA NA
- [1] "10" "20" "10"
- [1] 1 2 1
A factor is stored as integer codes pointing into its levels ("10", "20"), and as.numeric() returns those codes: 1 2 1. To get the original numbers convert via the labels:
as.numeric(as.character(f)) or as.numeric(levels(f))[f].What does this code print?
mean(1, 2, 3)- [1] 2
- [1] 1
- [1] 6
- Error: unused arguments (2, 3)
mean() averages its *first* argument only; 2 and 3 are passed through
... and matched to other parameters (trim and na.rm) instead of being averaged. The result is the mean of 1, i.e. 1 — with no error. Write mean(c(1, 2, 3)) to get 2. (By contrast, sum(1, 2, 3) is 6, because sum() adds all its arguments.)Как проходить тест
- Выберите темы и уровень — лёгкий уровень проверяет определения и задачи в одно действие, средний — стандартные вычисления, сложный — многошаговые задачи и теорию.
- Отвечайте касанием или с клавиатуры: 1–4 или A–D, Enter — следующий вопрос.
- Читайте объяснения — после ошибки разбор открывается сразу, после верного ответа его можно раскрыть кнопкой «Почему».
- Работайте над ошибками — «Повторить ошибки» в конце теста или режим «Только мои ошибки» потом: ответы запоминаются в этом браузере.
Незавершённый тест сохраняется — после перезагрузки страницы можно продолжить с того же вопроса.
Темы теста
- Vectors and recycling 9
- Data types and coercion 9
- Indexing and subsetting 9
- Lists and data frames 9
- Functions and scoping 9
- Control flow and apply family 9
- Strings and regex 9
- Statistics and distributions 9
- Models 9
- Packages and the tidyverse 9
- Gotchas 10
Другие тесты
Тест по линейной алгебре160 вопросовТест по дифференциальным уравнениям130 вопросовТест по теории вероятностей и статистике130 вопросовТест по SAS100 вопросовТест по LaTeX100 вопросовТест по системам компьютерной алгебры100 вопросовТест по Fortran120 вопросовТест по языку C100 вопросовТест по COBOL100 вопросовТест по MATLAB100 вопросовТест по PowerBuilder100 вопросовТест по UNIX100 вопросов
