简体   繁体   English

如何在一个循环中获取多个矩阵并自动分配它们?

[英]How do I get multiple matrices within a loop and assign them automatically?

I have a list containing 15 different groups that I want to convert into 15 different matrices in a for loop. 我有一个包含15个不同组的列表,我想在for循环中将其转换为15个不同的矩阵。 However, I could not make it work. 但是,我无法使其工作。

a=split(datalist,as.factor(datalist$groups))

When I do this I can visualize different groups by typing a[1] a[2] etc. my each a component (a[1], a[2] etc) were in a list and have size of 3x24 and they were considered as non-numeric. 当我这样做时,我可以通过键入a [1] a [2]等来可视化不同的组。我的每个组件(a [1],a [2]等)都在列表中,大小为3x24,并被认为是为非数字。 I get these components after using split command. 我在使用split命令后得到了这些组件。 but I need them as numeric that is why I thought I need to convert them into matrices and for that, I try to make a loop which converts those components into 15 different matrices which are 3x24 in size. 但是我需要将它们作为数字,这就是为什么我认为我需要将它们转换为矩阵的原因,为此,我尝试制作一个循环,将这些分量转换为大小为3x24的15个不同的矩阵。

for each i number (from 1 to 15) I can get a matrix by using 对于每个i数(从1到15),我可以通过使用

matrix(unlist(a[i]), ncol=columnlength,byrow=rowlength)

this command. 此命令。

Then I start my loop 然后我开始循环

    for (i in 1:15) {
  b[i]=matrix(unlist(a[i]), ncol=24,byrow=3)

    }

It is wrong since I am using b[i] which specifies only one unit of a matrix. 这是错误的,因为我使用的b [i]仅指定矩阵的一个单位。 But I do not know what to use instead of b[i]. 但是我不知道用什么代替b [i]。

I can't understand your problm. 我不明白你的问题。

a=split(datalist,as.factor(datalist$groups))

the "a" result is an vector or matrix|data.frame? “ a”结果是矢量还是矩阵| data.frame?

then you crate "b" matrix, 3x24 然后创建3x24的“ b”矩阵

you want put every "a" element into "b" matrix, right? 您想将每个“ a”元素放入“ b”矩阵中,对吗?

your "a" have 24 elements with 3 element each? 您的“ a”有24个元素,每个元素有3个元素? (like a matrix...) (如矩阵...)

b <- as.matrix(a)

cannot resolve your problem? 无法解决您的问题?

Here's an approach I show using mtcars 这是我使用mtcars展示的一种方法

First, split like you're already doing 首先,像您已经做的那样拆分

split.df <- split(mtcars, mtcars$cyl)

Then, create new variables labeled a thru letters[N] 然后,创建标记a直通letters[N]新变量letters[N]

newnames <- letters[1:length(split.df)]

Use assign to <- the variable name and data 使用assign<-变量名和数据

for (x in 1:length(newnames)) {
      assign(newnames[x], as.matrix(split.df[[x]]))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM