How to operate on an array row by row or column by column in R language?
In R language, loop structures can be used to iterate through rows or columns of an array. For example, we can use a for loop to iterate through rows of a two-dimensional array (matrix).
# 创建一个3x3的矩阵
mat <- matrix(1:9, nrow=3)
# 逐行对矩阵进行操作
for (i in 1:nrow(mat)) {
row <- mat[i,]
# 在这里对每一行进行操作
print(row)
}
To operate on a matrix column by column, you can adjust the loop range to the number of columns.
# 逐列对矩阵进行操作
for (j in 1:ncol(mat)) {
col <- mat[,j]
# 在这里对每一列进行操作
print(col)
}
In addition to using loops, you can also use the apply function to perform row or column operations on matrices. For example, you can use the apply function to calculate the sum of each row in a matrix.
# 对矩阵逐行求和
rowSums <- apply(mat, 1, sum)
print(rowSums)
Similarly, the apply function can be used to operate on a matrix column by column.
# 对矩阵逐列求和
colSums <- apply(mat, 2, sum)
print(colSums)