2013-03-15 63 views
0

我已经预先分配了一个3D数组,并尝试用数据填充它。但是,每当我使用先前定义的data.frame串进行此操作时,数组会被神秘地转换为列表,这会弄乱所有内容。将data.frame collumn转换为向量不会有帮助。在R中填充3D数组:如何避免强制列表?

例子:

exampleArray <- array(dim=c(3,4,6)) 
exampleArray[2,3,] <- c(1:6) # direct filling works perfectly 

exampleArray 
str(exampleArray) # output as expected 

问题:

exampleArray <- array(dim=c(3,4,6)) 
exampleContent <- as.vector(as.data.frame(c(1:6))) 
exampleArray[2,3,] <- exampleContent # filling array from a data.frame column 
# no errors or warnings 

exampleArray  
str(exampleArray) # list-like output! 

有没有什么办法可以解决这个问题,通常填补我的阵列?

感谢您的建议!

回答

1

试试这个:

exampleArray <- array(dim=c(3,4,6)) 
exampleContent <- as.data.frame(c(1:6)) 
> exampleContent[,1] 
[1] 1 2 3 4 5 6 
exampleArray[2,3,] <- exampleContent[,1] # take the desired column 
# no errors or warnings 
str(exampleArray) 
int [1:3, 1:4, 1:6] NA NA NA NA NA NA NA 1 NA NA ... 

你试图在数组中插入数据帧,这是行不通的。您应该使用dataframe$columndataframe[,1]

此外,as.vector不会做任何as.vector(as.data.frame(c(1:6))),你as.vector(as.data.frame(c(1:6)))后很可能,虽然不工作:

as.vector(as.data.frame(c(1:6))) 
Error: (list) object cannot be coerced to type 'double' 
+0

好了,所以小“”使其中的差别!非常感谢你! – jgoldmann 2013-03-15 11:57:20