【问题标题】:Avoid collpasing dimensions when omitting NAs from array从数组中省略 NA 时避免折叠维度
【发布时间】:2018-10-18 06:05:27
【问题描述】:

我有一个数组,我必须省略 NA 值。我知道这是一个充满矩阵的数组,其中每一行都有一个 NA 值。我的方法适用于 >2 列的矩阵,但 apply() 在只有两列时会下降一维(因为在省略 NA 值后,一列会消失)。 由于这一步是更大代码的一部分,我想避免重新编码其余部分,并使这一步对列数为 2 的情况具有鲁棒性。这是一个简单的例子:

#create an array
arr1 <- array(rnorm(3000),c(500,2,3))

#randomly distribute 1 NA value per row of the array
for(i in 1:500){
arr1[i,,sample(3,1)] <- NA
}

#omit the NAs from the array
arr1.apply <- apply(arr1, c(1,2),na.omit)

#we lose no dimension as every dimension >1
dim(arr1.apply)
[1]   2 500   2


#now repeat with a 500x2x2 array

#create an array
arr2 <- array(rnorm(2000),c(500,2,2))

#randomly distribute 1 NA value per row of the array
for(i in 1:500){
  arr2[i,,sample(2,1)] <- NA
}

#omit the NAs from the array
arr2.apply <- apply(arr2, c(1,2),na.omit)

#we lose one dimension because the last dimension collapses to size 1
dim(arr2.apply)
[1] 500   2

我不希望 apply() 删除最后一个维度,因为它破坏了我的其余代码。

我知道这是apply() 的一个已知问题,但是,我渴望在这一步中解决问题,因此我们将不胜感激。到目前为止,我已经尝试使用应该产生的维度将 apply() 包装在 array() 命令中,但是,我认为这以一种不可取的方式混合了矩阵中的值。

感谢您的帮助。

【问题讨论】:

  • 是否有特定的理由使用数组而不是列表、矩阵、数据框?
  • 我得到的输入文件是数组的形式,但是,可以将它们转换为列表,然后再转换回数组。结果必须是数组形式。
  • 一切都好,只需使用此代码:apply(arr1,3,function(x) na.omit(x)) 即可消除数组中每个矩阵的 NA。这样,对于数组中的每个矩阵,它将分别删除 NA 行,希望能如愿以偿!
  • 该死的阵列。
  • 知道那种感觉。

标签: arrays r apply dimension


【解决方案1】:

我提出了一个愚蠢的解决方案,但如果你想保持这种方式,我认为你别无选择:

arr1.apply <- if(dim(arr1)[3] > 2){
apply(arr1, c(1,2),na.omit)} else{
array(apply(arr1, c(1,2),na.omit),dim = c(1,dim(arr1)[1:2]))}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 2020-11-18
    • 2020-04-23
    • 2013-06-20
    • 1970-01-01
    • 2011-11-15
    • 2011-11-17
    相关资源
    最近更新 更多