【问题标题】:Apply on two similar lists gives two different results应用于两个相似的列表会给出两个不同的结果
【发布时间】:2014-11-23 02:00:19
【问题描述】:

我创建了一个函数来计算一个叫做“参与系数”的值,并用一个简短的列表测试了这个函数,就像这样

testList<-c(568120,711503,1077594)
testResults<-(sapply(testList, function(x) participationCoefficient(x)))

这给了我:

> testResults
               [,1]           [,2]            [,3]
[1,] 568120.0000000 711503.0000000 1077594.0000000
[2,]      0.7333333      0.8780488       0.4166667

现在,当我尝试从其他来源创建列表时

>authList<-moduleCalcs[[x]]$authId
> authList[1:5]
[1] 548114 553928 553929 556071 559044

并使用apply函数

> testResults<-(sapply(authList, function(y) participationCoefficient(y)))

我明白了

Error in provideDimnames(x) : 
  length of 'dimnames' [1] not equal to array extent
Called from: top level

所以我尝试发送一个缩短的 authList,但我仍然收到相同的错误。我对这里发生的事情有点困惑。

另外,这里是函数的代码,以备不时之需

participationCoefficient<-function(auth){
  outmod<-as.data.frame(table(subset(m2$moduleId.x,(m2$A2==auth | m2$A1==auth) & m2$moduleId.y!=m2$moduleId.x)))
  deg<-nrow(subset(m2,m2$A1==auth | m2$A2==auth))
  partcoef<-1-(Reduce("+",(outmod$Freq/deg)))
  answer<-c(auth,partcoef)
  rm(deg,outmod,partcoef)
  return(answer)
}

知道为什么会发生这种情况吗?

编辑

这里有一些可用于 m2 的数据。我不确定这是否是分享它的最佳方式。如果没有,请告诉我是否有其他方法。

authList
[1] 548114 553928

 A2 A1  moduleId.x   moduleId.y
1013122 553928  1   1
1066822 548114  1   1
548114  722690  1   1
548114  666417  1   1
548114  854300  1   1
548114  842554  1   1
548114  991715  1   1
553928  710558  1   1
553928  767591  2   1
553928  718371  1   1
553928  649043  1   1
553928  601167  1   1
553928  637192  2   1
553928  710304  1   1
553928  559044  1   1
563965  553928  1   1
571821  553928  1   1
661623  553928  1   1
682197  553928  1   1
682886  553928  1   1
683583  553928  1   1
712141  553928  1   1
716224  553928  1   1
723022  553928  1   1
851338  553928  1   1
934132  553928  1   1
995296  553928  1   1

【问题讨论】:

  • 您的错误不是reproducible。您的函数使用未定义的变量m2。请花时间提供一个示例,我们可以复制/粘贴以重新创建错误。这将使帮助您变得更加容易。将您的代码简化到触发错误的最低限度。
  • 请参阅我在how to make a reproducible example 上提供的链接中的示例,了解包含示例数据的更好方法。 dput() 比原始数据更容易处理。

标签: r function sapply


【解决方案1】:

在这个特定的例子中发生的事情是这里的子集命令

outmod<-as.data.frame(table(subset(m2$moduleId.x,(m2$A2==auth | m2$A1==auth) & m2$moduleId.y!=m2$moduleId.x)))

返回一个空集,这导致表函数出现问题。我不得不在函数中添加一个条件语句来防止这种可能性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    相关资源
    最近更新 更多