R当列表包含“不同大小”的对象时,将列表转换为矩阵 [英] R Turning a list into a matrix when the list contains objects of "different size"
问题描述
我已经看到关于将矩阵转换成列表的几个问题(不太清楚你为什么要这样做),但是我无法找到的相反的操作。
I've seen a couple of questions about turning matrices into lists (not really clear why you would want that) but the reverse operation I've been unable to find.
基本上,以下
# ind.dum = data frame with 29 observations and 2635 variables
for (i in 1:ncol(ind.dum))
tmp[[i]]<-which(rollapply(ind.dum[,i],4,identical,c(1,0,0,0),by.column=T))
我得到一个2635个对象的列表,其中大多数包含1个值,突破一些高达7.我需要将其转换为具有2635行和尽可能多列的矩阵,以适应单独单元格中的每个值(带有0个值对于其余的)。
I got a list of 2635 objects, most of which contain 1 value, bust some up to 7. I'd need to convert this to a matrix with 2635 rows and as many columns as necessary to fit every value in a separate cells (with 0 values for the rest).
我尝试了所有的胁迫措施,我知道( as.data.frame
as.matrix
...),还可以选择定义最大尺寸的新矩阵,但无效。
I tried all the coerce measures I know (as.data.frame
, as.matrix
...) and also the option to define a new matrix with the maximum dimensions but nothing works.
m<-matrix(0,nrow=2635,ncol=7)
tmp_m<-structure(tmp,dim=dim(m))
Error in structure(tmp,dim=dim(m))dims [product 18445] do not match the length of object [2635]
我确定有一个快速的修复,所以我希望有人可以帮助我。 Btw,我的tmp列表对象中的值是数字的,尽管有些是integer(0),即当在原始的ind.dum矩阵的列中没有找到模式c(1,0,0,0)时。
I'm sure there's a quick fix for this so I'm hoping someone can help me with it. Btw, my values in the tmp list's objects are numeric, although some are "integer(0)" , i.e. when the pattern c(1,0,0,0) was not found in the columns of the original ind.dum matrix.
不知道有没有办法使用 unlist
而不会丢失关于哪些属性原来属于同一个属性的信息行...
Not sure if there is a way to use unlist
without losing the information about which values belong originally to the same row...
期望的输出
具有2635行和7列的矩阵或数据框,如下所示
Desired Output A matrix or dataframe with 2635 rows and 7 columns and looking like this
12 0 0 0 0 0 0
8 14 0 0 0 0 0
0 0 0 0 0 0 0
1 4 8 12 0 0 0
...
这些值基本上是到具体模式开始的几年。我需要能够使用该信息将此问题与之前描述的早期问题相结合(见这个链接)。
The values basically refer to years in which a specific pattern started. I need to be able to be able to use that information to tie this problem to an earlier problem described before (see this link).
推荐答案
尝试这个例子:
do.call(rbind,lapply(ll,
function(x)
if(length(x)==1)c(x,rep(0,6))
else x))
这篇关于R当列表包含“不同大小”的对象时,将列表转换为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!