R基础元素

这一章的主要内容是向量、缺失值、矩阵和索引。主要内容是用英文书写,是笔者一边学习一边整理的,在理解上应该不存在难度。建议在掌握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-Infand 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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容