0

我的代码有一个小问题。这是我的代码示例。当我运行该函数时,我得到以下结果。另外,我正在使用raply()fromplyr包,此函数将输出作为列表数组返回。我的代码

EmpPval<-function(dat,numberOfPermutations=100,usePlyr=TRUE)

{

  if(usePlyr)
  {
    require(plyr)
  }

   if(usePlyr)
  {

statistic <- raply(numberOfPermutations,permdat(dat)$statistic,.progress="tk")
    browser()
  }

  else
  {    
    statistic <- replicate(expr=permdat(dat)$statistic,n=numberOfPermutations,
                           simplify=TRUE)
  }

 }

>statistic   #this is from one iteration

    [1] 0.0409457

    attr(,"numerator")

    [1] 0.0007954759

    attr(,"denominator")

    [1] 0.01942758

我的结果有属性。现在我的问题是我无法将这些值存储在变量中,我想像这样再次访问它们:

s1<-attr(statistic,"numerator")

s2<-attr(statistic,"denominator") 

permdat()for 循环中运行。所以我将生成 100 个这样的值,并且我想存储所有 100 个统计值及其属性。我现在得到的是这样的:

>statistic ##this is after it runs in a loop

[1] 0.028793900 [2] 0.073739396 [3] 0.049136225 [4] 0.058408310 [5] 0.027253176 [6] 0.019471812 [7] 0.071434025 [8] 0.038411458 [9] 0.028921401 [10] 0.021929506..... The attribute values are not stored. 

有人可以帮我吗?提前致谢。

4

1 回答 1

0

您可以将结果存储permdat(dat)$statistic在列表中而不是向量中。这将保留所有属性。

我强烈建议使用replicate而不是,raply因为后者会删除属性。如果您指定simplify = FALSE,结果将存储在列表中并保留所有属性。

statistic <- replicate(expr = permdat(dat)$statistic, n = numberOfPermutations,
                       simplify = FALSE)

现在您可以使用 访问单个列表对象"[[",例如statistic[[1]]将返回第一个对象及其属性。

您可以返回具有以下值的向量unlist

unlist(statistic)

具有属性的向量可以通过以下方式返回sapply

sapply(statistic, attr, "numerator")

sapply(statistic, attr, "denominator")

如果您想更轻松地访问数据,可以创建一个新对象s2

s2 <- unlist(statistic)
attributes(s2, "numerator") <- sapply(statistic, attr, "numerator")
attributes(s2, "denominator") <- sapply(statistic, attr, "denominator")

现在,您可以简单地使用:

attr(s2, "numerator")
attr(s2, "denominator") 
于 2013-02-27T08:43:41.030 回答