coursera R Programming NOTE(1)

R Nuts and Bolts

Entering Input

x <- 1 #The <- symbol is the assignment operator.

Evaluation

When a complete expression is entered at the prompt, it is evaluated and the result of the evaluated
expression is returned.

R Objects

R has five basic or “atomic” classes of objects:

  • character
  • numeric (real numbers)
  • integer
  • complex
  • logical (True/False)

vector:

A vector can only contain objects of the same class.

Numbers

Numbers in R a generally treated as numeric objects (i.e. double precision real numbers).
If you explicitly want an integer, you need to specify the L suffix.
Inf represents infinity;can be used in ordinary calculations
NaN an undefined value (“not a number”); e.g. 0 / 0

Attributes

  • names, dimnames
  • dimensions (e.g. matrices, arrays)
  • class (e.g. integer, numeric)
  • length
  • other user-defined attributes/metadata

Creating Vectors

c() function
vector() function
x <- vector("numeric", length = 10)

Mixing Objects

implicit coercion

y <- c(1.7, "a") ## character
y <- c(TRUE, 2) ## numeric
y <- c("a", TRUE) ## character

Explicit Coercion

as.* functions
as.numeric(x)
as.logical(x)
as.character(x)

Matrices

m <- matrix(nrow = 2, ncol = 3)
m <- matrix(1:6, nrow = 2, ncol = 3)
Matrices are constructed column-wise, so entries can be thought of starting in the “upper left” corner and running down the columns.

m <- 1:10
dim(m) <- c(2, 5)

cbind()
rbind()

Lists

Lists are a special type of vector that can contain elements of different classes.
x <- list(1, "a", TRUE, 1 + 4i)
x <- vector("list", length = 5) # create an empty list of a prespecified length

Factors

x <- factor(c("yes", "yes", "no", "yes", "no"))
x <- factor(c("yes", "yes", "no", "yes", "no"), levels = c("yes", "no"))

Missing Values

Missing values are denoted by NA or NaN for q undefined mathematical operations.

  • is.na() is used to test objects if they are NA
  • is.nan() is used to test for NaN
  • NA values have a class also, so there are integer NA, character NA, etc.
  • A NaN value is also NA but the converse is not true

Data Frames

x <- data.frame(foo = 1:4, bar = c(T, T, F, F))

Names

vector list names()

Object Set column names Set row names
data frame names row.names()
matrix colnames() rownames()

你可能感兴趣的:(coursera R Programming NOTE(1))