R语言学习_创建数据集

本文介绍了R语言中创建数据集的三种方式:使用matrix、array和data.frame。详细讲解了它们的语法格式,并通过实例展示了如何创建和操作这些数据结构。还提及了ncdf4包在处理.nc格式数据时的一些常用函数。

创建数据集总纲
数据结构
matrix语法格式
mymatrix <- matrix(vector, nrow = number_of_rows, ncol = number_of_columns, byrow = logical_value, dimnames = list(char_vector_rownames, char_vector_colnames))

vector包含了矩阵的元素。
nrow和ncol用以指定行和列的维数。
dimnames包含了可选的、以字符型向量表示的行名和列名。
byrow则表明矩阵应当按行填充(byrow = TRUE)还是按列填充(byrow = FALSE)

示例

rnames <- c(“A1”,“A2”,“A3”)
cnames <- c(“一月”,“二月”,“三月”)
mymatrix <- matrix(1:9, nrow = 3, ncol = 3, byrow = FALSE, dimnames = list(rnames, cnames))
mymatrix
一月 二月 三月
A1 1 4 7
A2 2 5 8
A3 3 6 9

数组array语法格式:
myarray <- array(vector, dimensions, dimnames)
其中vector包含了数组中的数据
dimensions是一个数值型向量,给出了各个维度下标的最大值
dimnames是可选的、各维度名称标签的列表。

dim1 <- c(“A1”,“A2”)
dim2 <- c(“B1”,“B2”,“B3”)
dim3 <- c(“C1”,“C2”,“C3”,“C4”)
myarray <- array(1:50, c(2,3,4), dimnames = list(dim1, dim2, dim3))
myarray
, , C1

B1 B2 B3
A1 1 3 5
A2 2 4 6

, , C2

B1 B2 B3
A1 7 9 11
A2 8 10 12

, , C3

B1 B2 B3
A1 13 15 17
A2 14 16 18

, , C4

B1 B2 B3
A1 19 21 23
A2 20 22 24

data.frame()语法格式:
mydata <- data.frame(col1, col2, col3, …)

patientID <- c(1,2,3,4)
age <- c(25,34,29,53)
diabetes <- c(“Type1”,“Type2”,“Type3”,“Type4”)
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 29 Type3 Excellent
4 4 53 Type4 Poor
patientda

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值