R语言实战2:数据结构
2019-05-17 本文已影响0人
冬之心
title: "R语言实战2:数据结构"
author: "wintryheart"
date: "2019年5月17日"
output: html_document
knitr::opts_chunk$set(echo = TRUE)
第2章 创建数据集
2.1 数据集的概念
各行业对数据集的行和列的不同叫法:
行业 | 行 | 列 |
---|---|---|
统计学 | 观测(observation) | 变量(variable) |
数据库 | 记录(record) | 字段(field) |
数据挖掘和机器学习 | 示例(example) | 属性(attribute) |
2.2 数据结构
名称 | 含义 | 特征 | 创建函数 | 备注 |
---|---|---|---|---|
向量 | 一维数组 | 数据必须是同类型 | c() | |
矩阵 | 二维数组 | 数据必须是同类型 | matrix() | 参数dimnames=list()以字符型给行和列命名 |
数组 | 维度可以大于2 | 数据必须是同类型 | array() | 参数dimnames=list()以字符型给维度命名 |
数据框 | 类似STATA中的数据集 | 不同列可以是不同数据类型 | data.frame() | |
因子 | 类别变量和有序类别变量 | 以一个整数向量存储名义类别 | factor() | 参数ordered=TRUE指定有序 |
列表 | 对象的有序集合 | 允许整合若干对象到单个对象名下 | list() |
实例
# 向量
a <- c(1, 2, 3)
b <- c("best", "better", "good")
c <- c(TRUE, FALSE, TRUE)
a
b
c
# 矩阵
x <- matrix(1:20, nrow=5, ncol=4)
y1 <- matrix(1:20, nrow=5, ncol=4, byrow = TRUE)
y2 <- matrix(1:20, nrow=5, ncol=4, byrow = FALSE)
x
y1
y2
rnames <- c("R1", "R2")
cnames <- c("C1", "C2")
y3 <- matrix(1:20, nrow=2, ncol=2, dimnames = list(rnames, cnames))
y3
# 数组
dim1 <- c("A1", "A2")
dim2 <- c("B1", "B2", "B3")
dim3 <- c("C1", "C2", "C3", "C4")
array1 <- array(1:24, c(2,3,4))
array1
array2 <- array(1:24, c(2,3,4), dimnames= list(dim1, dim2, dim3))
array2
#数据框
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
#选取行
patientdata[1:2]
#选取列
patientdata[c("diabetes", "status")]
#交叉表
table(patientdata$diabetes, patientdata$status)
# attach(), detach()和with()
attach(patientdata)
summary(age)
detach(patientdata)
with(patientdata, {
summary(age)
})
#with()创建的对象只在括号内有效。
#如果要创建with()结构以外存在的对象,使用特殊赋值符 <<- 代替标准赋值符 <-
with(patientdata, {
inkeep <- summary(age)
outkeep <<- summary(age)
})
outkeep
#因子
attach(patientdata)
diabetes
diabetes <- factor(diabetes)
diabetes
status
status <- factor(status, ordered = TRUE)
status
#自定义排序
status <- factor(status, ordered = TRUE, levels = c("Poor", "Improved", "Excellent"))
status
#显示对象的结构
str(patientdata)
summary(patientdata)
#列表
g <- "My list"
h <- c(25, 26, 18 ,39)
j <- matrix(1:10, nrow=5)
k <- c("one", "two", "three")
mylist <- list(title=g, age=h, j, k)
mylist
#显示列表中的某个对象
mylist[[2]]
mylist[["age"]]
2.3 数据输入
数据 | 函数 | 所需的包 | 备注 |
---|---|---|---|
键盘输入 | edit() | 必须先生成空表 | |
带分隔符的文本 | read.table(file, options) | ||
Excel | read.xlsx(file, n) | xlsx包 | n表示要导入的工作表序号 |
网页数据 | RCurl包和XML包,rvest包 | ||
SPSS | read.spss() | foreign包 | |
SPSS | spss.get() | Hmic包 | |
STATA | read.dta() | foreign包 |
2.4数据集的标注
- 变量标签:不支持
- 值标签: factor()函数中的labels参数
patientdata$gender <- c(1,2,1,1)
patientdata$gender <- factor(patientdata$gender, levels=c(1,2), labels=c("male", "female"))
patientdata["gender"]