使用生成的列表元素打印正确的列表索引



只是为了好玩,我写了一个简短的函数,每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]]))来代替上面的print调用,但是这会改变输出格式。

您可以重新定义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)返回默认行为。

最新更新