使用结果列表元素打印正确的列表索引

时间:2014-08-24 22:33:03

标签: r

为了好玩,我写了一个简短的函数,每8秒打印一次R fortune

myFortuneFn <- function() {
    require(fortunes)
    l <- lapply(seq_len(nrow(read.fortunes())), fortune)
    print(l[1])
    for(i in seq_along(l)[-1]){
        Sys.sleep(8)
        print(l[i])
    }
}

该功能打印正确的财富,但我希望列表索引按顺序保存并打印当前财富的正确索引。意味着在下面的第二个结果(在第一个结果后8秒),应该有[[2]]作为索引,而不是[[1]]。这应该是l

的结尾
> myFortuneFn()
# [[1]]
# 
# Okay, let's stand up and be counted: who has been writing diamond graph code? Mine's 60 lines.
#    -- Barry Rowlingson (in a discussion about the patent for diamond graphs)
#       R-help (August 2003)
#
#
# [[1]] ## <- this should read [[2]], and so on all the way to [[360]]
#
# Bug, undocumented behaviour, feature? I don't know. It all seems to work in 1.6.0, so everyone should downgrade
# now... :)
#    -- Barry Rowlingson
#       R-help (July 2003)

如何修复打印,以便在打印命运时按顺序打印列表索引?我已尝试print(c(i, l[[i]]))代替上述{{1}调用,但这会改变输出格式。

1 个答案:

答案 0 :(得分:1)

您可以重新定义print.fortune以打印row.names属性给出的与财富相关联的财富编号:

require(fortunes)
print.fortune <- function(x){
  cat(paste0('[[',attr(x, "row.names"),']]'))
  cat('\n')
  fortunes:::print.fortune(x)
}
myFortuneFn <- function() {
  l <- lapply(seq_len(nrow(read.fortunes())), fortune)
  for(i in seq_along(l)){
    print(l[[i]])
    Sys.sleep(8)
  }
}


> myFortuneFn()
[[1]]

Okay, let's stand up and be counted: who has been writing diamond graph code? Mine's 60
lines.
   -- Barry Rowlingson (in a discussion about the patent for diamond graphs)
      R-help (August 2003)

[[2]]

Bug, undocumented behaviour, feature? I don't know. It all seems to work in 1.6.0, so
everyone should downgrade now... :)
   -- Barry Rowlingson
      R-help (July 2003)

当您完成重新调整用途的功能后,您当然可以rm(print.fortune)返回默认行为。