Subsetting

Basics

[] will return object of the same type, can be used to select more than one element.

[[]] will access an element on exact position.

$ will access named variable, for example in a list.

Partial Matching

R will guess name of variable when we use $ operator.

> x <- list(aardvark = 1:5)
> x$a
[1] 1 2 3 4 5
> x[["a"]]
NULL
> x[["a", exact = FALSE]]
[1] 1 2 3 4 5

Examples

First we create a table with random values.

Here is how that table could look like.

Return first column by index. When we pass a number, it will return column from that position.

Return column by name.

Return column by name and rows by position.

Filter by column values using logical operator AND.

Filter by column values using logical operator OR.

If tehre is missing value in the data set and we do not want to return it, we have to use which function.

Visually compare what is returned by the query above and the query below, which is not using which function..

Sort values by column.

Sort values by column and place "NA" values at the end.

Order data by a column.

Ordering with plyr library.

Adding columns

or

Last updated

Was this helpful?