Day_1 Part_4 Structures of R

2023-11-06

1. Vector/Matrix/Array

1.1. What are they

  • Collection of observations
    – Vector – 1 dimensional
    – Matrix – 2 dimensional
    – Array – 3 dimensional
  • Class in vector/matrix/array
    – Only one class per object
    – Combined – class determined: factor/logical < integer < numeric < character (当出现一个vector/matrix/array 里面有多种class的数据时,决定顺序如上。比如一个character + numeric最后的class是character)
    example:

1.2. Vector

1.2.1 Generate Vector

> vec1 <- c(1, 2, 3)
> vec2 <- 1:11

> vec3 <- rep(x = 4, 7)
> vec3
[1] 4 4 4 4 4 4 4

> vec4 <- seq(from = 1, to = 12, by = 1.333)
> vec4
[1]  1.000  2.333  3.666  4.999  6.332  7.665  8.998 10.331 11.664

> vec5 <- seq(1, 12, lenght.out = 10) # 1到12之间,等分取10个数
## Warning: In seq.default(1, 12, lenght.out = 10) :
## extra argument 'lenght.out' will be disregarded
> vec5     #即1, 1+(12-1)/(10-1), 1+2*[(12-1)/(10-1)], ..., 1+(10-1)*[(12-1)/(10-1)]
[1]  1.000000  2.222222  3.444444  4.666667  5.888889  7.111111  8.333333 
[8]  9.555556 10.777778 12.000000

1.2.2 Index Vector

  • Indexing by []
  • 负号 - 在R的索引里意味着去除该元素
  • 区别于其他语言, R 的索引是从1开始的

Example

> vec4
[1]  1.000  2.333  3.666  4.999  6.332  7.665  8.998 10.331 11.664

vec4[3]
## [1] 3.666
vec4[1:3]
## [1] 1.000 2.333 3.666
vec4[23:24]
## [1] NA NA

vec4[c(1, 3, 7)]
## [1] 1.000 3.666 8.998
vec4[c(1, 1, 1, 2)]
## [1] 1.000 1.000 1.000 2.333

vec4[-4]     #access everything but the 4th element
## [1] 1.000 2.333 3.666 6.332 7.665 8.998 10.331 11.664

vec4[-1:3] # this will cause error
## Error in vec4[-1, 3] : 量度数目不对
# It’s related to the way -1:3 is interpreted.
-1:3
## [1] -1 0 1 2 3

vec4[-(1:3)]  #brackets will help negate all elements of 1:3
## [1] 4.999 6.332 7.665 8.998 10.331 11.664
vec4[-c(4, 5, 7)]
## [1] 1.000 2.333 3.666 7.665 10.331 11.664

vec4[9:1] #listing the vector in reverse
## [1] 11.664 10.331 8.998 7.665 6.332 4.999 3.666 2.333 1.000

1.3. Matrix

1.3.1. Generate Matrix

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
参数:

参数 description
data an optional data vector (including a list or expression vector). Non-atomic classed R objects are coerced by as.vector and all attributes discarded.
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. 即 byrow=T 是横着往里填数据,byrow=F 是竖着往里填数据
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.
> MT <- matrix(c(1,2,1,2),nrow=2,ncol=2,byrow=T)
> MT
    [,1] [,2]
[1,] 1 2
[2,] 1 2

# another example
> MT2<-matrix(c(1,2,1,2),nrow=3,ncol=5,byrow=F)
Warning message:
In matrix(c(1, 2, 1, 2), nrow = 3, ncol = 5, byrow = F):数据长度[4]不是矩阵行数[3]的整倍
> MT2
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    1    2    1
[2,]    2    1    2    1    2
[3,]    1    2    1    2    1

1.3.2. Index Matrix

用法:matrix[row,column]

> MT[1,1] #即取第一行第一列的元素。
[1] 1

1.4. Array

1.4.1. Generate Array

array(data = NA, dim = length(data), dimnames = NULL)

参数 description
data a vector (including a list or expression vector) giving data to fill the array. Non-atomic classed objects are coerced by as.vector.
dim the dim attribute for the array to be created, that is an integer vector of length one or more giving the maximal indices in each dimension.
dimnames either NULL or the names for the dimensions. This must a list (or it will be ignored) with one component for each dimension, either NULL or a character vector of the length given by dim for that dimension. The list can be named, and the list names will be used as names for the dimensions. If the list is shorter than the number of dimensions, it is extended by NULLs to the length required.
> ARR <- array(1:4, c(1,2,2)) #参数 c(1,2,2) 意思是1个row, 2个col, 2个layer。填入的数据是1:4。
> ARR
,,1
	[,1] [,2]
[1,] 1 2
,,2
	[,1] [,2]
[1,] 3 4

1.4.2. Index Array

Array[row,column,layer]

> ARR[1,2,2]
[1] 4
> ARR[1,1,2]
[1] 3
> ARR[1,1,1]
[1] 1
> ARR[1,2,1]
[1] 2

1.5. Arithmetic for matrix and arrays

Operations Function
Number of rows/colums nrow(x)/ncol(x)
Length of all elements length(x)
Names of rows and columns names()
Dimension ; 对于array返回(row,col,layer) dim()
Transpose t(x)
Matrix multiplication x %*% y
Cross product crossprod(x,y)
Diagonal elements diag(x)

NB:
(1)t(x) 这里有一篇文章讲的很清楚:http://blog.sciencenet.cn/blog-508298-551299.html
(2) x %*% y 矩阵乘法;crossprod(x,y)俩矩阵的向量积

2. list

2.1. Description:

  • Collection of variables
    – Different classes/structures are possible (可以将不同结构的数据放在一个list中,甚至list里面嵌套list。如一个list里一层是dataframe,一层是array,一层是plot/list)
    – Different dimensions is possible

2.2. Generate & Index List

Created with list()
Indexed with [[ ]]

# create
my_character <-c(1, 1, 0, 0)
my_logical <- TRUE
> my_list <- list(my_character, my_logical)
> my_list
 	[[1]]
[1] 1 1 0 0

	[[2]]
[1]  TRUE

# index
> my_list[[1]]
[1] “1” “1” “0” “0”
> my_list[[1]][3]
[1] “0

3. Dataframe

3.1. Description:

  • Variables in data frame can have different classes
  • ncol(x)/nrow(x) returns number of columns/rows
  • Columns and rows are named - colnames/rownames

3.2. Generate Dataframe

生成:
data.frame(..., row.names = NULL, check.rows = FALSE, check.names = TRUE, fix.empty.names = TRUE, stringsAsFactors = default.stringsAsFactors())
参数表:

参数 description
... these arguments are of either the form value or tag = value. Component names are created based on the tag (if present) or the deparsed argument itself.
row.names NULL or a single integer or character string specifying a column to be used as row names, or a character or integer vector giving the row names for the data frame.
check.rows if TRUE then the rows are checked for consistency of length and names.
check.names logical. If TRUE then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names and are not duplicated. If necessary they are adjusted (by make.names) so that they are.
fix.empty.names logical indicating if arguments which are “unnamed” (in the sense of not being formally called as someName = arg) get an automatically constructed name or rather name “”. Needs to be set to FALSE even when check.names is false if “” names should be kept.
stringsAsFactors logical: should character vectors be converted to factors? The ‘factory-fresh’ default has been TRUE previously but has been changed to FALSE for R 4.0.0. Only as short time workaround, you can revert by setting options(stringsAsFactors = TRUE) which now warns about its deprecation.

Example:

> data <- data.frame(ID=rep(1:10, each=3),
					 TIME=c(0,6,12),
					 MDV=0)
> str(data)
'data.frame': 30 obs. of 3 variables:
$ ID : int 1 1 1 2 2 2 3 3 3 4 ...
$ TIME: num 0 6 12 0 6 12 0 6 12 0 ...
$ MDV : num 0 0 0 0 0 0 0 0 0 0 ...

3.3. Index Dataframe

用法:
dataframe[row,column]
dataframe$colname[row]

Example:

> data[3,2]
[1] 12

> data$TIME[3]
[1] 12

> data$TIME[data$TIME==12] <- 12.5 #把data$TIME里的12都换成12.5
> data$TIME
 [1]  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5
[22]  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5
> data[ ,2]
 [1]  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5
[22]  0.0  6.0 12.5  0.0  6.0 12.5  0.0  6.0 12.5

> data[3,]
  ID TIME MDV
3  1 12.5   0

3.4. View data frames

Function Description
View(data.set) Open and look at data.set
head(data.set) Look at the first several lines of a data.set
tail(data.set) Look at the last several lines of a data.set
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Day_1 Part_4 Structures of R 的相关文章

  • R语言与数据分析实战4-变量的创建与修改

    第1关 创建新变量 在进行实际的数据分析时 我们会经常需要创建新变量或者为当前存在的变量变换新的取值 这就好比你是一个厨师 现在你要创新菜式 需要做一些新的厨房模具或者是改良当前已有的厨具来进行烹饪 对于创建新变量 其实原理非常简单 大家只
  • Navicat for MySQL客户端启动报missing required library libmysq_e.dll126 错误

    Navicat for MySQL客户端启动报missing required library libmysq e dll126 错误 是因为缺少libmysq e dll 文件所致 下载libmysq e dll 文件拷贝到到Navica
  • Rstudio更换主题/样式

    github项目地址 https github com gadenbuie rsthemes 安装 在 rstudio 的控制台console中数据 install packages devtools devtools install gi
  • R语言基本函数的学习(持续更新)

    目录 前言 Tidyverse包 arrange 函数 head 函数 filter 函数 select 函数
  • 看书标记【R语言数据分析与挖掘实战】4

    第四章 数据预处理 4 1 数据清洗 缺失值处理 使用is na 判断缺失值是否存在 complete cases 可以识别样本数据是否完整从而判断缺失情况 删除法 na omit 函数移除所有含有缺失数据的行 data p 删除p列 替换
  • R语言作图:坐标轴设置

    R语言作图 坐标轴设置 偷闲阁 2018 02 04 20 51 24 209654 收藏 359 分类专栏 R语言 可视化 文章标签 R 坐标轴 刻度 可视化 版权声明 本文为博主原创文章 遵循 C
  • 三句话,我让R语言自动升级了

    R语言是为数学研究工作者设计的一种数学编程语言 主要用于统计分析 绘图 数据挖掘 跟所有计算机语言一样 R语言也面临升级的问题 本文讲述了最快捷的升级R语言办法 不用重新安装之前的安装包 首先 进入R交互模式 然后三条命令搞定 instal
  • 如何用R分析CNKI文献关键词词频?

    疑惑 如何用VOSviewer分析CNKI数据 一文发布后 有同学问我 王老师 我有个问题 我用cnki导出关键词后 想统计关键词的词频 我应该用什么样的工具 如果不利用citespace和python 做出excel那种的统计表格 该怎么
  • 如何编写R函数

    转载自http blog sciencenet cn blog 255662 501317 html R语言实际上是函数的集合 用户可以使用base stats等包中的基本函数 也可以自己编写函数完成一定的功能 但是初学者往往认为编写R函数
  • ggplot2作图之系统发育树

    library ape tree lt read tree text A B C D E F G H I J K L M N O P library ggtree ggtree tree branch length none ladderi
  • SQL中去掉字符串中最后一个字符(小技巧)

    长度减一就可以了 select left 字段名 len 字段名 1 from 表名
  • 使用R语言中的survival包进行生存分析是一种常见的统计方法

    使用R语言中的survival包进行生存分析是一种常见的统计方法 在生存分析中 我们经常需要创建一个生存对象来存储事件发生时间和事件状态 在本文中 我们将介绍如何使用survival包中的Surv函数来创建生存对象 并解读其结果 Surv函
  • R语言基础——缺失数据

    R语言基础 缺失数据 缺失数据的分类 统计学家通常将缺失数据分为三类 它们都用概率术语进行描述 但思想都非常直观 我们将用sleep研究中对做梦时长的测量 有12个动物有缺失值 来依次阐述三种类型 1 完全随机缺失 若某变量的缺失数据与其他
  • R语言应用序列模式挖掘揭示客户购买行为:深度学习与机器学习的视角

    目录 序列模式挖掘 一个简介 使用R进行序列模式挖掘 应用深度学习和机器学习改善购买行为预测
  • Class 06 - 良好的编码习惯(保持代码的可读性)

    Class 06 良好的编码习惯 保持代码的可读性 保持代码的可读性 编码风格 命名的注意事项 文件名 对象名称 语法 运算符 逗号 中括号和小括号 大括号 代码缩进 代码的长度 赋值 注释 调试报错 保持代码的可读性 在编写 R语言 或任
  • R语言 write.xlsx() 写入同一excel,及同一sheet注意

    write xlsx x file sheetName Sheet1 col names TRUE row names TRUE append FALSE showNA TRUE 1 想要将data1写da xlsx的sheet1 data
  • 2021-05-03

    一 R中安装 phyloseq 的方法 很多网上的教程使用的都是 source https bioconductor org biocLite R biocLite phyloseq 但是我尝试了很多次 最后还是没有成功 下面能成功安装 p
  • 计算机科学丛书(2014-2018.Q1)

    ISBN 名称 作者 出版时间 978 7 111 53451 8 数学设计和计算机体系结构 原书第2版 美 戴维 莫尼 哈里斯 莎拉 L 哈里斯著 978 7 111 44075 8 嵌入式计算系统设计原理 美 Marilyn Wolf著
  • R语言实现推荐系统

    目录 1 理论基础 1 1 推荐系统 1 2 R语言 2 数据准备 2 1 数据获取 2 2 数据读取
  • 4. 统计描述和基线表格绘制

    目录 1 连续型变量统计描述 单变量统计描述 1 summary函数 2 psych包中的describe 函数 3 Hmisc包中的describe 函数 4 pastecs包的stat desc 的函数 分组统计描述 1 doBy包的s

随机推荐

  • 《因果学习周刊》第6期:因果推荐系统

    No 06 智源社区 因果学习组 因 果 学 习 研究 观点 资源 活动 关于周刊 因果学习作为人工智能领域研究热点之一 其研究进展与成果也引发了众多关注 为帮助研究与工程人员了解该领域的相关进展和资讯 智源社区结合领域内容 撰写了第6期
  • 【GeekUninstaller】卸载程序

    软件介绍 删除不了的文件 或者软件可以下载试试不需要安装 文章目录 前言 一 如何下载 二 使用步骤 1 安装完之后自动打开 前言 GeekUninstallers是一款高效 快速 小巧 免费的软件卸载与清理工具 旨在帮助用户删除系统上安装
  • caffe源码追踪--syncedmem

    首先来看看caffe include caffe syncedmem hpp ifndef CAFFE SYNCEDMEM HPP define CAFFE SYNCEDMEM HPP include
  • 深度学习之 python pandas

    在数据科学领域 pandas是非常有用的工具 在数据科学细分领域大数据 通常和深度学习有关 这部分 本篇博客从pandas重要函数开始 到数据变换以及数据分析 pandas提供了数据变换 数据清理 数据可视化以及数据提取等主要数据处理功能
  • tar -xf_linux 解压缩命令tar

    linux环境下常见的压缩文件格式 tar tar gz tar bz2 tar xz 参数 c create create a new archive 创建文件 x extract get extract files from an ar
  • 静态资源上传七牛云

    一 七牛云SDK function 请参考demo的index js中的initQiniu 方法 若在使用处对options进行了赋值 则此处config不需要赋默认值 init options 即updateConfigWithOptio
  • Python爬虫实战(五) :下载百度贴吧帖子里的所有图片

    准备工作 目标网址 https tieba baidu com p 5113603072 目的 下载该页面上的所有楼层里的照片 第一步 分析网页源码 火狐浏览器 gt 在该页面上右击 查看页面源代码 会打开一个新的标签页 第二步 查找图片源
  • ue4蓝图中的customevent和function的细微差别。

    在调用第三方库时 我用customEvent时 可以调用LowEntryHttpRequest中的 Executes the request This blueprint can NOT execute several HTTP Reque
  • 记录一下浏览器缩放和移动端缩放的区别,其实两者是有很大的不同的,之前一直搞不明白。

    直接问AI它们之间的区别的话 是这么回答的 浏览器缩放和移动端缩放是两种不同的概念 它们涉及到用户在不同设备上改变网页内容大小的方式 以下是它们的主要区别 浏览器缩放 Desktop Browser Zoom 浏览器缩放是指在桌面计算机浏览
  • 以太坊学习计划1

    1 如果链接远程链 需要上链才可以 打开服务才可以 2 开启本地geth 服务 下载https geth ethereum org downloads 默认启动geth服务 不启动rpc服务 手动用命令行启动 geth rpc 代码端调用
  • C++的使用小教程8——多态与接口

    C 的使用小教程8 多态与接口 1 什么是多态与接口 2 实现方式 3 应用实例 学习好幸苦 1 什么是多态与接口 C 多态意味着调用成员函数时 会根据调用函数的对象的类型来执行不同的函数 接口描述了类的行为和功能 而不需要完成类的特定实现
  • Qgis国际化

    参考文章 QT实现多国语言 几点需要注意的 1 pro文件生成方法 2 ts文件生成方法 输入命令 lupdate f code QT Code QtApplication2 QtApplication2 QtApplication pro
  • Vit,DeiT,DeepViT,CaiT,CPVT,CVT,CeiT简介

    Vit 最基础的 就是将transformer的encoder取出来 输入图像大小维度 B C H W 将图片不重叠地划分为H patch height w patch weight个patch 每个patch为patch height p
  • Spark相关问题

    Spark相关问题 Hadoop FileFormat接口问题 Hadoop FileOutputFormat在写入数据的时候先写到临时目录 最后写入最终目录 临时目录到最终目录的过程中需要做文件树合并 合并过程中有大量Rename操作 F
  • Hash函数

    概述 Hash函数 散列函数 是一种将任意长度的数据映射到有限长度的域上 通俗来讲 就是将一串任意长度的数据进行打乱混合 转换为一段固定长度的数据输出 这段数据便成为输入数据的一个 指纹 特征 Hash函数的首要目标是保证数据的完整性 而不
  • css连续的纯数字或字母强制换行

    white space normal word break break all
  • 一些网站1

    N1BOOK平台 Nu1L Team Nu1L Team 0004 Median of Two Sorted Arrays LeetCode Cookbook 题库 力扣 LeetCode 全球极客挚爱的技术成长平台
  • 解决shell断开后java进程被结束

    偶尔会碰到用SecureCRT在shell启动java进程并后台运行 命令最后加 的时候 因为断电死机等原因断开shell 然后进程被结束了 运维大佬也说用他们的工具启动进程后一断开连接进程就结束了 后来查到是因为shell在断开的时候会向
  • 漫谈数据挖掘从入门到进阶

    做数据挖掘也有些年头了 写这篇文一方面是写篇文 给有个朋友作为数据挖掘方面的参考 另一方面也是有抛砖引玉之意 希望能够和一些大牛交流 相互促进 让大家见笑了 入门 数据挖掘入门的书籍 中文的大体有这些 Jiawei Han的 数据挖掘概念与
  • Day_1 Part_4 Structures of R

    1 Vector Matrix Array 1 1 What are they Collection of observations Vector 1 dimensional Matrix 2 dimensional Array 3 dim