本篇文章由 VeriMake 旧版论坛中备份出的原帖的 Markdown 源码生成

原帖标题为:R 语言 | 数组
原帖网址为:https://verimake.com/topics/225 (旧版论坛网址,已失效)

原帖作者为:dawdler(旧版论坛 id = 64,注册于 2020-08-17 14:01:22)
原帖由作者初次发表于 2021-05-29 16:56:41,最后编辑于 2021-05-29 16:56:41(编辑时间可能不准确)

截至 2021-12-18 14:27:30 备份数据库时,原帖已获得 361 次浏览、0 个点赞、0 条回复


R 数组

创建与访问数组

前一期讲到矩阵,其实矩阵,就是一个二维的数组。所以这一期,我们会更多地以三维或更多维的数组来举例。

R语言中,我们使用array()函数来创建新的数组,并且可以使用dim =设置数组维度:

##create 
v1 <- c(2,4,6)
v2 <- c(1,3,5,7,9,11)

#create a 2-dimension 3x3 array by v1 and v2
v1v2 <- array(c(v1,v2),dim=c(3,3,2))
print(v1v2)

#the same array but is created with labels
column.names <- c("col1","col2","col3")
row.names <- c("row1","raw2","raw3")
matrix.names <- c("m1","m2")
v1v2 <- array(c(v1,v2),dim=c(3,3,2),dimnames=list(row.names,column.names,matrix.names))
print(v1v2)

以上代码的输出结果为:

下面是一个三维数组定义的例子:

##create 
 #dim=c(2,3,4): four 2x3 matrices
m <- array(1:24, dim=c(2,3,4))
print(m)
#access elements
 #print the elements at i=1,2; j=2; k=2,3
print(m[,2,2:3])
 #print third matrix
print(m[,,3])
 #element at row=1, col=2 in the third matrix
print(m[1,2,3])
 #each element at row=1, col=2 in the four matrices
print(m[1,2,])

以上代码的输出结果为:

提示:为了方便理解,我们将一个二维的数组,即一个矩阵,放在平面直角坐标系中,row对应y轴坐标,column对应x轴坐标,那么对于一个三维的数组,我们可以借助一个0-xyz空间直角坐标系,依旧让row对应y轴坐标,column对应x轴坐标,然后我们可以想象在z轴上,每个单位上都是一个矩阵,就像一片一片切片面包整整齐齐排在z轴上形成了一块完整的面包条。

2. 操作数组

在上面访问三维数组的示例中可以看到,我们在实际运用中可以单独提取z轴上每个矩阵中同一位置的数,当我们想对这样跨纬度提取出的数进行算数计算时,可以借助apply(x, margin, function)函数,其中x是要操作的目标数组,margin是定义按行计算或按列计算,1-按行,2-按列,function是要调用的的算术函数。

#operations
m <- array(1:24, dim=c(2,3,4))
print(m)
 #compute sum of numbers by row
s1 <- apply(m,1,sum)
 #compute sum of numbers by column
s2 <- apply(m,2,sum)
 #sum of numbers in row1 is 144
 #sum of numbers in row2 is 156
print(s1)
 #sum of numbers in column1 is 84
 #sum of numbers in column2 is 100
 #sum of numbers in column3 is 116
print(s2)

以上代码的输出结果为:

相关资料:
https://www.math.pku.edu.cn/teachers/lidf/docs/Rbook/html/_Rbook/prog-type-matrix.html#p-t-array-apply

说点什么吧...

qZMtmT.png网站备案号:ICP备16046599号-1