这一章的主要内容是向量、缺失值、矩阵和索引。主要内容是用英文书写,是笔者一边学习一边整理的,在理解上应该不存在难度。建议在掌握R中基本的赋值和四则运算语法后学习,了解R中的基本运算单位。
Sequences of number
paste(my_name,collapse = " ")
paste("Hello", "world!", sep = " ")
the first line of code will join the strings in my_name into one strings.and the second line will join different strings from different vectors into one.
Vector
Vectors come in two different flavors: atomic vectors and lists. An atomic vector contains exactly one data type, whereas a list may contain multiple data types. We'll explore atomic vectors further before we get to lists.
In previous lessons, we dealt entirely with numeric vectors, which are one type of atomic vector. Other types of atomic vectors include logic, character, integer and complex. In this lesson, we'll take a closer look at logical and character vector.
Logical vectors can contain the values TRUE, FALSE, and NA (for 'not available'). These values are generated as the result of logical 'conditions'.
The <
and >=
symbols in these examples are called 'logical operators'. Other logical operators include >
, <=
, ==
for exact equality, and !=
for inequality.
If we have two logical expressions, A and B, we can ask whether at least one is TRUE with A | B (logical 'or' a.k.a. 'union') or whether they are both TRUE with A & B (logical 'and' a.k.a. 'intersection'). Lastly, !A is the negation of A and is TRUE when A is FALSE and vice versa(反之亦然).
Missing Value
Missing values play an important role in statistics and data analysis. Often, missing values must not be ignored, but rather they should be carefully studied to see if there's an underlying pattern or cause for their missingness.
In R, NA is used to represent any value that is 'not available' or 'missing' (in the statistical sense). In this lesson, we'll explore missing values further.
NA
which stands for 'not avaliable'
to find NA
in variable(let's take it as x), we have
is.na(x)
Everywhere you see a TRUE, you know the corresponding element of x is NA. Likewise, everywhere you see a FALSE, you know the corresponding element of x is a non-NA.
NA
is not really a value, if we code
x == NA
all we have can only be--R has no choice but to return a vector of the same length as x that contains all NAs.
NAN
which stands for 'not a number', such as 0/0
or Inf-Inf
and so on (Inf means infinity)
Subsetting Vectors
In this lesson, we'll see how to extract(取出) elements from a vector based on some conditions that we specify.
For example, we may only be interested in the first 20 elements of a vector, or only the elements that are not NA, or only those that are positive or correspond to a specific variable of interest. By the end of this lesson, you'll know how to handle each of these scenarios.
The way you tell R that you want to select some particular elements (i.e. a 'subset') from a vector is by placing an 'index vector' in square brackets
(方括号)immediately following the name of the vector. For example,
try x[1:10]
to view the first ten elements of x
As already shown, to subset just the first ten values of x using x[1:10]. In this case, we're providing a vector of positive integers inside of the square brackets, which tells R to return only the elements of x numbered 1 through 10.
Many programming languages use what's called 'zero-based indexing', which means that the first element of a vector is considered element 0. R uses 'one-based indexing', which (you guessed it!) means the first element of a vector is considered element 1.
Index vectors come in four different flavors -- logical vectors, vectors of positive integers, vectors of negative integers, and vectors of character strings -- each of which we'll cover in this lesson.
indexing with logical vectors
Let's start by indexing with logical vectors. One common scenario(情景) when working with real-world data is that we want to extract all elements of a vector that are not NA (i.e. missing data). Recall that is.na(x) yields a vector of logical values the same length as x, with TRUEs corresponding to NA values in x and FALSEs corresponding to non-NA values in x.
To view all the "NAs" in x
x[is.na(x)]
To view all the "non-NAs" in x, and put them in y. Then to find the positive values in y.
y <- x[!is.na(x)]
y[y>0]
But if we try x[x>0
directly ,we get a bunch of NAs mixed in with our positive numbers since "NA" is not really a number.
So, what about x[!is.na(x)&x>0]
, it's the same with y[y>0]
.
positive integer, and negative integer
To subset the 3rd, 5th, and 7th elements of x
x[c(3,5,7)]
It's important that when using integer vectors to subset our vector x, we stick with the set of indexes {1, 2, ..., 40} since x only has 40 elements or we get only "NA" which might be useless in most cases.
by
x[c(-2,-10)]
or
x[-c(2,10)]
we can get all elements of x EXCEPT for the 2nd and 10 elements.
Named Elements
To create "named" vectors
vect <- c(foo = 11, bar = 2, norf = NA)
vect2 <- c(11, 2, NA)
names(vect2) <- c("foo","bar","norf")
now we have both vect and vext2, use
identical(vect, vect2)
to see if they were the same.
To Find Elements by Name
such as by using vect[c("bar","foo") ]
we get 2 11
.
Matrices and Data Frame
Matrices:only contain a single class of data
Data Frame:consist of many different classes of data
Matrix
dim(x)
:to view the dimensions of x
To give a vector dim, we have
dim(x) <- c(4,5)
this will turn a vector to a matrix.
use class(x)
to say the type of x.
Instead of what we mention above, we can create matrix directly by
matrix(data, nrow, ncol)
use the cbind()
function to 'combine columns'.
data frame
To create a data frame, use
my_data <- data.frame(patients, my_matrix)
where patients is a vector and my_matrix is matrix in this case.
cnames <- c("patient","age", "weight", "bp", "rating", "test")
colnames(my_data) <- cnames
we can simply assigning names to the columns of our data frame.
Logic
Logic Operators
Creating logical expressions requires logical operators. You're probably familiar with arithmetic operators like +
, -
, *
, and /
. The first logical operator we are going to discuss is the equality operator, represented by two equals signs ==
.
<=
: less than or equal to
<
:less than
>=
:greater than or equal to
>
:greater than
!=
:not equal to
&
and&&
TRUE & c(TRUE, FALSE, FALSE)
TRUE && c(TRUE, FALSE, FALSE)
use the &
operator to evaluate AND across a vector. The &&
version of AND only evaluates the first member of a vector.
the **Or operator **|
and||
work just like the 'and' operator but with a different meaning.
arithmetic has an order of operations and so do logical expressions. All AND operators are evaluated before OR operators.
Let's see
5 > 8|| 6!=8 && 4>3.9
this gonna return to a "TRUE"
function
isTRUE(x)
will tell us if x is true
identical()
will return TRUE if the two R objects passed to it as arguments are identical.
xor()
function stands for exclusive OR. If one argument evaluates to TRUE and one argument evaluates to FALSE, then this function will return TRUE, otherwise it will return FALSE.
now we use
ints <- sample(10)
to create a vector which contains a random sampling of integers from 1 to 10 without replacement.
then which(ints > 7)
will give us the indices(检索) to the elements which are greater 7 in ints.
any()
function will return TRUE if one or more of the elements in the logical vector is TRUE.
all()
function will return TRUE if every element in the logical vector is TRUE.
Let's try
any(ints < 0)
all(ints > 0)