[英]How to add to a list of matrices in R?
Given a dataset 'train'
that has 1607
rows and 256
columns, I want to make each row (with 256
elements each) a 16x16
matrix and have a list to hold 1607
of such matrices. 给定一个具有
1607
行和256
列的数据集'train'
,我想使每一行(每个具有256
元素)为16x16
矩阵,并具有一个列表来容纳1607
个此类矩阵。 All observations in the train
data are values between -1
and 1
. train
数据中的所有观测值均为-1
和1
之间的值。 For example, a row vector in the train
could be 例如,
train
的行向量可以是
a <- seq(from = -1, to = 1, length = 256)
When I try to run a loop like this, 当我尝试运行这样的循环时,
x <- lapply(1:nrow(train), matrix, data=0, nrow=16, ncol=16) #creates list of 1607 matrices of 0's
for (i in length(x)) {
x[[i]] <- matrix(X_train[i,], nrow=16, ncol=16) #replace each element (matrix) of list x with a matrix of the same dimension from train
}
I keep getting the same unmodified list x
with matrices of 0
for all elements of x
. 我不断收到同样的未修改列表
x
与矩阵0
的所有元素x
。 What am I doing wrong? 我究竟做错了什么?
for (i in length(x)) {
Here, you are looping over one value, namely, length(x)
. 在这里,您正在遍历一个值,即
length(x)
。 You probably want to loop over all values from 1 to the length of x
. 您可能希望遍历从1到
x
长度的所有值。 You do this with 你这样做
for (i in 1:length(x)) {
or 要么
for (i in seq_along(x)) {
The latter has the benefit that it won't produce a bad result if x
is empty. 后者的好处是,如果
x
为空,则不会产生不良结果。 But really, you don't need to make a loop at all, or produce a list of blank matrices which you immediately discard. 但是实际上,您根本不需要进行循环,也不需要产生立即丢弃的空白矩阵列表。 Instead, do:
相反,请执行以下操作:
rows <- seq_len(nrow(X_train))
x <- lapply(rows, function(row) matrix(X_train[row, ], nrow=16, ncol=16))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.