从 R 中的矩阵获取特定位置的元素
在任何时间点,可能需要遍历矩阵以查找特定位置的元素。在本文中,我们将使用整数向量、逻辑向量作为索引访问 R 编程语言中矩阵中的元素。
方法一:使用整数向量访问元素
整数向量是一个向量,包含所有整数类型的元素。
句法:
matrix_name[row_vector_with_values,column_vector_with_values,]
例子:
select rows 1 & 3 and columns 1 & 3 of matrix a.
print(a )
程序:
R
# create a vector named data with 9 elements
data=c(1,2,3,4,5,6,7,8,9)
# pass this vector to matrix input
a=matrix(data, nrow = 3, ncol = 3)
print(a)
# select rows 1 & 3 and columns 1 & 3
print(a[c(1,3),c(1,3)] )
# select rows 1 & 2 and columns 1 & 2
print(a[c(1,2),c(1,2)] )
# select rows 2 & 1 and columns 2 & 2
print(a[c(2,1),c(2,2)] )
R
# create a vector named data with 9 elements
data=c(1,2,3,4,5,6,7,8,9)
# pass this vector to matrix input
a=matrix(data, nrow = 3, ncol = 3)
print(a)
a[c(TRUE, FALSE,TRUE, FALSE,TRUE, FALSE,TRUE, FALSE,TRUE)]
# accessing elements
R
# create a vector named data with 9 elements
data=c(1,2,3,4,5,6,7,8,9)
# pass this vector to matrix input
a=matrix(data, nrow = 3, ncol = 3)
print(a)
print(a[c(TRUE)])
# accessing elements by placing all TRUE
print(a[c(FALSE)])
# accessing elements by placing all FALSE
输出:
方法二:使用逻辑向量访问矩阵元素
逻辑向量包括包含布尔值的向量,即真或假。
句法 :
matrix_name[logical_vector]
如果在该位置为 TRUE,则访问矩阵元素
如果在该位置为 FALSE,则不访问矩阵元素。
例子:
data=c(TRUE,TRUE,FALSE)
方案一:
电阻
# create a vector named data with 9 elements
data=c(1,2,3,4,5,6,7,8,9)
# pass this vector to matrix input
a=matrix(data, nrow = 3, ncol = 3)
print(a)
a[c(TRUE, FALSE,TRUE, FALSE,TRUE, FALSE,TRUE, FALSE,TRUE)]
# accessing elements
输出:
方案二:
电阻
# create a vector named data with 9 elements
data=c(1,2,3,4,5,6,7,8,9)
# pass this vector to matrix input
a=matrix(data, nrow = 3, ncol = 3)
print(a)
print(a[c(TRUE)])
# accessing elements by placing all TRUE
print(a[c(FALSE)])
# accessing elements by placing all FALSE
输出: