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

R 使用生成的列表元素打印正确的列表索引,r,R,为了好玩,我编写了一个短函数,每8秒打印一次下一个Rfortune 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秒打印一次下一个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])
    }
}

如何修复打印,以便在打印财富时按顺序打印列表索引?我尝试了
print(c(I,l[[I]])
来代替上述
print
调用,但这会改变输出格式。

您可以重新定义
print.fortune
,以打印与
行中给出的财富相关联的财富编号。name
属性:

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)
require(财富)

print.fortune
l[i]
是一个包含单个元素的列表。您可以使用
l[[i]]
这是属于
fortune
类的,并且具有
attr(l[[i]],“row.names”)
。目前,
l[[i]]
是使用
getAnywhere(print.fortune)
打印的,因此您可以重新定义
print.fortune
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)