在R中填充3D数组:如何避免强制列出?

时间:2013-03-15 11:41:05

标签: r list multidimensional-array coercion

我已预先分配了一个3D数组并尝试用数据填充它。但是,每当我使用先前定义的data.frame collumn执行此操作时,数组会神秘地转换为列表,这会弄乱所有内容。将data.frame collumn转换为向量对它没有帮助。

示例:

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 个答案:

答案 0 :(得分: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'