代码之家  ›  专栏  ›  技术社区  ›  nouse

使用Lappy将数据帧列表写入文件:如何将对象名称粘贴到文件名?

  •  5
  • nouse  · 技术社区  · 7 年前

    我有一个数据帧列表:

    lists <- replicate(10, as.data.frame(matrix(rnorm(100), 10, 10)), simplify = FALSE)
    names(lists) <- LETTERS[1:10]
    

    我想将所有数据帧写入一个单独的文件,该文件根据R中的对象名称命名 lapply 具有 paste ,但这一点严重失败:

    lapply(lists, function(x) write.table(x, file=paste(x,".txt"), sep="\t"))
    Error in file(file, ifelse(append, "a", "w")) : 
      invalid 'description' argument
    In addition: Warning message:
    In if (file == "") file <- stdout() else if (is.character(file)) { :
      the condition has length > 1 and only the first element will be used
    Called from: file(file, ifelse(append, "a", "w"))
    

    如何在不为n个数据写入n个单行的情况下执行此操作。帧?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Florian    7 年前

    您正在遍历列表元素,而不是列表元素的名称。所以表达式 paste(x,".txt") 尝试粘贴 data.frame .txt ,但要将列表元素的名称粘贴到 .txt文件 . 因此,您可以尝试以下操作:

    lists <- replicate(10, as.data.frame(matrix(rnorm(100), 10, 10)), simplify = FALSE)
    names(lists) <- LETTERS[1:10]
    
    lapply(names(lists), function(x) write.table(lists[[x]], file=paste(x,".txt"), sep="\t"))
    

    要抑制控制台输出,请将语句包装在 invisible() ,或者使用常规for循环:

    for (x in names(lists))
      write.table(lists[[x]], file=paste(x,".txt"), sep="\t")