Basic R functions

| category RStudy  | tag R

1. all, any, which

x = -5:5

all(x)  # Given a set of logical vectors, are all of the values true?

[1] FALSE

all(x > 3)

[1] FALSE


any(x)  # Given a set of logical vectors, is at least one of the values true?

[1] TRUE

any(x > 3)

[1] TRUE


which(x > 3)  # Give the TRUE indices of a logical object, allowing for array indices.

[1] 10 11

x[which(x > 3)]

[1] 4 5

x[x > 3]

[1] 4 5


which.max(x)  # Give the indices of max

[1] 11

x[which.max(x)]

[1] 5

max(x)

[1] 5


which.min(x)  # Give the indices of min

[1] 1

x[which.min(x)]

[1] -5

min(x)

[1] -5


2. summary, max, min, mean, median, range, quantile

options(digits = 4)
y = rnorm(10)
y

[1] -0.4460 -0.2693 -0.1460 -1.9396 -0.0134  0.1919  0.4205  0.5393
[9]  0.2638  0.9963

summary(y)

Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-1.9400 -0.2380  0.0893 -0.0402  0.3810  0.9960

max(y)

[1] 0.9963

min(y)

[1] -1.94

mean(y)

[1] -0.04025

median(y)

[1] 0.08926

range(y)

[1] -1.9396  0.9963

quantile(y, c(0.25, 0.75, 0.95))

25%     75%     95%
-0.2384  0.3813  0.7906



3. dim, nrow, ncol, colMeans, colSums, rowMeans, rowSums

df = data.frame(x = 1:5, y = 3:7, z = 23:27)
df

x y  z
1 1 3 23
2 2 4 24
3 3 5 25
4 4 6 26
5 5 7 27


dim(df)

[1] 5 3

nrow(df)

[1] 5

ncol(df)

[1] 3


colMeans(df)

x  y  z
3  5 25

colSums(df)

x   y   z
15  25 125

rowMeans(df)

[1]  9 10 11 12 13

rowSums(df)

[1] 27 30 33 36 39


4. nchar, strsplit, substr, toupper, tolower

z = "Hello World"
nchar(z)

[1] 11

strsplit(z, " ")

[[1]]
[1] "Hello" "World"

substr(z, 1, 1)

[1] "H"

substr(z, 1, 3)

[1] "Hel"

toupper(z)

[1] "HELLO WORLD"

tolower(z)

[1] "hello world"


5. cummax, cummin, cumprod, and cumsum

x = c(1, 2, -3, 4, -6, 9, 6, 7)
x

[1]  1  2 -3  4 -6  9  6  7

cumsum(x)

[1]  1  3  0  4 -2  7 13 20

cumprod(x)

[1]     1     2    -6   -24   144  1296  7776 54432

cummax(x)

[1] 1 2 2 4 4 9 9 9

cummin(x)

[1]  1  1 -3 -3 -6 -6 -6 -6


6. diff, duplicated, unique, order, and sort

x = c(1, 0, -2, 3, 6, 0, 9)
x

[1]  1  0 -2  3  6  0  9


diff(x, 1)  # x[i] - x[i-1]

[1] -1 -2  5  3 -6  9


duplicated(x)

[1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE

x[!duplicated(x)]

[1]  1  0 -2  3  6  9


unique(x)

[1]  1  0 -2  3  6  9


order(x)

[1] 3 2 6 1 4 5 7

x[order(x)]

[1] -2  0  0  1  3  6  9


sort(x)

[1] -2  0  0  1  3  6  9


ifelse

a = c(4, -4)
sqrt(ifelse(a >= 0, a, NA))

[1]  2 NA


do.call

# Execute a Function Call
do.call(paste, list("Hello", "World", sep = " "))

[1] "Hello World"


x = seq(1, 2, by = 0.2)
y = seq(3, 4, by = 0.2)
do.call(cbind, list(x, y))

[,1] [,2]
[1,]  1.0  3.0
[2,]  1.2  3.2
[3,]  1.4  3.4
[4,]  1.6  3.6
[5,]  1.8  3.8
[6,]  2.0  4.0

do.call(rbind, list(x, y))

[,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1  1.2  1.4  1.6  1.8    2
[2,]    3  3.2  3.4  3.6  3.8    4


expression and eval

# Evaluate an (Unevaluated) Expression
x = 3
y = 5
z = expression(x + y)
z

expression(x + y)

eval(z)

[1] 8