coursera R Programming NOTE(1)

2015-10-20  本文已影响0人  pipi636

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:

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

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.

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()
上一篇 下一篇

猜你喜欢

热点阅读