2.1 数据集的概念

不同的行业对于数据集的行和列叫法不同。统计学家称它们为观测(observation)和变量(variable),数据库分析师则称其为记录(record)和字段(field),数据挖掘和机器学习学科的研究者则把它们叫作示例(example)和属性(attribute)。
R中有许多用于存储数据的结构,包括标量、向量、数组、数据框和列表。多样化的数据结构赋予了R极其灵活的数据处理能力。
R可以处理的数据类型(模式)包括数值型、字符型、逻辑型(TRUE/FALSE)、复数型(虚数)和原生型(字节)。

2.2 数据结构

2.2.1 向量

  • 通过在方括号中给定元素所处位置的数值,访问向量中的元素
a <- c("k", "j", "h", "a", "c", "m")
a[3]
## [1] "h"
a[c(1, 3, 5)]
## [1] "k" "h" "c"

2.2.2 矩阵

  • matrix creates a matrix from the given set of values.
  • as.matrix attempts to turn its argument into a matrix.
  • is.matrix tests if its argument is a (strict) matrix.

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = list(char_vector_rownames, char_vector_colnames))

nrow: the desired number of rows.

ncol: the desired number of columns.

byrow: logical. If FALSE (the default) the matrix is filled by columns, otherwise the matrix is filled by rows.

dimnames:A dimnames attribute for the matrix: NULL or a list of length 2 giving the row and column names respectively. An empty list is treated as NULL, and a list of length one as row names. The list can be named, and the list names will be used as names for the dimensions.

  • as.matrix(x, rownames.force = NA, ...)

rownames.force:logical indicating if the resulting matrix should have character (rather than NULL) rownames. The default, NA, uses NULL rownames if the data frame has ‘automatic’ row.names or for a zero-row data frame.

  • is.matrix(x)

is.matrix returns TRUE if x is a vector and has a "dim" attribute of length 2 and FALSE otherwise. Note that a data.frame is not a matrix by this test.

rnames <- c("R1", "R2")
cnames <- c("C1", "C2")
y <- matrix(1:4, nrow=2, ncol=2, byrow=TRUE,dimnames=list(rnames, cnames))
y
## C1 C2
## R1 1 2
## R2 3 4
is.matrix(y)
## [1] TRUE

as.matrix is a generic function. The method for data frames will return a character matrix if there is only atomic columns and any non-(numeric/logical/complex) column, applying as.vector to factors and format to other non-character columns. Otherwise, the usual coercion hierarchy (logical < integer < double < complex) will be used, e.g., all-logical data frames will be coerced to a logical matrix, mixed logical-integer will give a integer matrix, etc.

da <- data.frame(
lot1 = c(1,2),
lot2 = c("a","b"))
ma<-as.matrix(da)
da
## lot1 lot2
## 1 1 a
## 2 2 b
ma
## lot1 lot2
## [1,] "1" "a"
## [2,] "2" "b"
str(da[1,1])
## num 1
str(ma[1,1])
## Named chr "1"
## - attr(*, "names")= chr "lot1"

如上例所示,数值型被转换为了字符型。

If you just want to convert a vector to a matrix, something like

  • dim(x) <- c(nx, ny)
  • dimnames(x) <- list(row_names, col_names)
x<-1:6
dim(x)<-c(2,3)
dimnames(x)<-list(c("a","b"),c("c","d","e"))
x
## c d e
## a 1 3 5
## b 2 4 6
  • 使用下标和方括号来选择矩阵中的行、列或元素

如x[2,]或者x[1,4],不需要像MATLAB用冒号表示整行或整列。

2.2.3 数组

数组(array)与矩阵类似,但是维度可以大于2。
  • myarray <- array(vector, dimensions, dimnames)

2.2.4 数据框

  • mydata <- data.frame(col1, col2, col3,...)
patientID <- c(1, 2, 3, 4)
age <- c(25, 34, 28, 52)
diabetes <- c("Type1", "Type2", "Type1", "Type1")
status <- c("Poor", "Improved", "Excellent", "Poor")
patientdata <- data.frame(patientID, age, diabetes, status)
patientdata
## patientID age diabetes status
## 1 1 25 Type1 Poor
## 2 2 34 Type2 Improved
## 3 3 28 Type1 Excellent
## 4 4 52 Type1 Poor
table(patientdata$diabetes, patientdata$status)
##
## Excellent Improved Poor
## Type1 1 0 2
## Type2 0 1 0

引用方法可以用列号patientdata[1:2],也可以用列名patientdata[c("diabetes", "status")],可以用$符号patientdata$age。

table用来生成列联表。

attach()

减少在每个变量名前键入数据框名的繁琐,将数据框添加到R的搜索路径中。R在遇到一个变量名以后,将检查搜索路径中的数据框。

例如:

attach(mtcars)
summary(mpg)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 10.40 15.43 19.20 20.09 22.80 33.90
plot(mpg, disp)
detach(mtcars)

datach()(将数据框从搜索路径中移除。

注意这样可能出现同名对象之间的屏蔽(mask)。

with()

with(mtcars, {
print(summary(mpg))
plot(mpg, disp)
})

花括号{ }之间的语句都针对数据框mtcars执行,无需担心名称冲突。

如果你需要创建在with()结构以外存在的对象,使用特殊赋值符<<-替代标准赋值符(<-)即可,它可将对象保存到with()之外的全局环境中。

实例标识符

在病例数据中,病人编号(patientID)用于区分数据集中不同的个体。在R中,实例标识符(case identifier)可通过数据框操作函数中的rowname选项指定。
patientdata <- data.frame(patientID, age, diabetes,
status, row.names=patientID)

2.2.5 因子

  • 名义型变量是没有顺序之分的类别变量。
  • 有序型变量表示一种顺序关系,而非数量关系。
  • 连续型变量可以呈现为某个范围内的任意值,并同时表示了顺序和数量。
类别(名义型)变量和有序类别(有序型)变量在R中称为因子(factor)。
  • factor() 以一个整数向量的形式存储类别值,由字符串(原始值)组成的内部向量将映射到这些整数上
  • 要表示有序型变量,需要为函数factor()指定参数ordered=TRUE

factor(x = character(), levels, labels = levels, exclude = NA, ordered = is.ordered(x), nmax = NA)

levels: an optional vector of the unique values (as character strings) that x might have taken. The default is the unique set of values taken by as.character(x), sorted into increasing order of x. Note that this set can be specified as smaller than sort(unique(x)).

labels: either an optional character vector of labels for the levels (in the same order as levels after removing those in exclude), or a character string of length 1. Duplicated values in labels can be used to map different values of x to the same factor level.

exclude: a vector of values to be excluded when forming the set of levels. This may be factor with the same level set as x or should be a character.

ordered: logical flag to determine if the levels should be regarded as ordered (in the order given), TRUE or FALSE.

nmax: an upper bound on the number of levels.

diabetes <- c("Type1", "Type2", "Type1", "Type1")
x<-factor(diabetes)
x
## [1] Type1 Type2 Type1 Type1
## Levels: Type1 Type2
str(x)
## Factor w/ 2 levels "Type1","Type2": 1 2 1 1
is.factor(x)
## [1] TRUE
as.integer(x)
## [1] 1 2 1 1
y<-factor(diabetes,levels=c("Type2","Type1"))
y
## [1] Type1 Type2 Type1 Type1
## Levels: Type2 Type1
z<-factor(diabetes,labels=c(2,1))
z
## [1] 2 1 2 2
## Levels: 2 1
ex<-factor(diabetes,exclude=c("Type1"))
ex
## [1] <NA> Type2 <NA> <NA>
## Levels: Type2

  





.nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
background: white;
border: 1px solid #ddd;
border-radius: 4px;
}

.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}

.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}

.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}

.tabset-dropdown > .nav-tabs > li.active {
display: block;
}

.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
}

.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}

.tabset-dropdown > .nav-tabs > li {
display: none;
}
-->

R语言实战(二) 创建数据集的更多相关文章

  1. R语言实战(一)介绍、数据集与图形初阶

    本文对应<R语言实战>前3章,因为里面大部分内容已经比较熟悉,所以在这里只是起一个索引的作用. 第1章       R语言介绍 获取帮助函数 help(), ? 查看函数帮助 exampl ...

  2. R语言实战(二)数据管理

    本文对应<R语言实战>第4章:基本数据管理:第5章:高级数据管理 创建新变量 #建议采用transform()函数 mydata <- transform(mydata, sumx ...

  3. R语言实战(七)图形进阶

    本文对应<R语言实战>第11章:中级绘图:第16章:高级图形进阶 基础图形一章,侧重展示单类别型或连续型变量的分布情况:中级绘图一章,侧重展示双变量间关系(二元关系)和多变量间关系(多元关 ...

  4. R 语言实战-Part 4 笔记

    R 语言实战(第二版) part 4 高级方法 -------------第13章 广义线性模型------------------ #前面分析了线性模型中的回归和方差分析,前提都是假设因变量服从正态 ...

  5. R 语言实战-Part 3 笔记

    R 语言实战(第二版) part 3 中级方法 -------------第8章 回归------------------ #概念:用一个或多个自变量(预测变量)来预测因变量(响应变量)的方法 #最常 ...

  6. R 语言实战-Part 5-1笔记

    R 语言实战(第二版) part 5-1 技能拓展 ----------第19章 使用ggplot2进行高级绘图------------------------- #R的四种图形系统: #①base: ...

  7. R语言实战(三)基本图形与基本统计分析

    本文对应<R语言实战>第6章:基本图形:第7章:基本统计分析 =============================================================== ...

  8. R语言实战(四)回归

    本文对应<R语言实战>第8章:回归 回归是一个广义的概念,通指那些用一个或多个预测变量(也称自变量或解释变量)来预测响应变量(也称因变量.效标变量或结果变量)的方法.通常,回归分析可以用来 ...

  9. R语言实战(八)广义线性模型

    本文对应<R语言实战>第13章:广义线性模型 广义线性模型扩展了线性模型的框架,包含了非正态因变量的分析. 两种流行模型:Logistic回归(因变量为类别型)和泊松回归(因变量为计数型) ...

  10. R语言实战(第二版)-part 1笔记

    说明: 1.本笔记对<R语言实战>一书有选择性的进行记录,仅用于个人的查漏补缺 2.将完全掌握的以及无实战需求的知识点略去 3.代码直接在Rsudio中运行学习 R语言实战(第二版) pa ...

随机推荐

  1. ML modeling process

    一.数据读取Load Data 二.数据分析EDA 三.数据预处理 四.特征工程Feature engineering 五.modeling & Tuning 六.Result 七.other ...

  2. CSS面试题&知识点汇总

    问题&答案 介绍一下标准的CSS的盒子模型?低版本IE的盒子模型有什么不同的? 有两种, IE 盒子模型.W3C 盒子模型: 盒模型: 内容(content).填充(padding).边界(m ...

  3. DOCKER中centos7的中文支持

    直接编写看下能否改变成识别中文字体 写到你的~/.bashrc里吧,然后重启终端(我写的是英文的啊,改成你要的) export LC_ALL=en_US.UTF-8 export LANGUAGE=e ...

  4. Nginx笔记总结十九:nginx + fancy实现漂亮的索引目录

    编译:./configure --prefix=/usr/local/nginx --add-module=../ngx-fancyindex-master 配置: location / { fanc ...

  5. linux安装fasttext报错,升级gcc后成功解决

    首先说一下存在问题: 本人打算在linux安装一个fasttext用来训练词向量,本来是想要从gensim来调用fasttext的,但是加载大的本地txt一直不对,没办法了只好在linux安装一个fa ...

  6. 从一道网易面试题浅谈 Tagged Pointer - darcy_tang 的博客

    前言 这篇博客九月就想写了,因为赶项目拖了到现在,抓住17年尾巴写吧~ 正文 上次看了一篇 <从一道网易面试题浅谈OC线程安全> 的博客,主要内容是: 作者去网易面试,面试官出了一道面试题 ...

  7. Springboot整合Dubbo和Zookeeper

    Dubbo是一款由阿里巴巴开发的远程服务调用框架(RPC),其可以透明化的调用远程服务,就像调用本地服务一样简单.截至目前,Dubbo发布了基于Spring Boot构建的版本,版本号为0.2.0,这 ...

  8. 添砖加瓦:Linux /proc目录简介

    Linux 内核提供了一种通过 /proc 文件系统,在运行时访问内核内部数据结构.改变内核设置的机制.proc文件系统是一个伪文件系统,它只存在内存当中,而不占用外存空间.它以文件系统的方式为访问系 ...

  9. Vue1.0用法详解

    Vue.js 不支持 IE8 及其以下版本,因为 Vue.js 使用了 IE8 不能实现的 ECMAScript 5 特性. 开发环境部署 可参考使用 vue+webpack. 基本用法 1 2 3 ...

  10. Java工厂模式解耦 —— 理解Spring IOC

    Java工厂模式解耦 -- 理解Spring IOC 最近看到一个很好的思想来理解Spring IOC,故记录下来. 资源获取方式 主动式:(要什么资源都自己创建) 被动式:(资源的获取不是我们创建, ...