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

编写data.frames列表,用lapply分隔CSV文件

r
  •  28
  • Chase  · 技术社区  · 15 年前

    这个问题说明了一切——我想把一个包含data.frames的列表对象写入一个单独的.csv文件,其中.csv文件的名称对应于列表对象的名称。

    这是一个可重复的例子和我迄今为止编写的代码。

    df <- data.frame(
        var1 = sample(1:10, 6, replace = TRUE)
        , var2 = sample(LETTERS[1:2], 6, replace = TRUE)
        , theday = c(1,1,2,2,3,3)
    )
    
    df.daily <- split(df, df$theday) #Split into separate days
    
    lapply(df.daily, function(x){write.table(x, file = paste(names(x), ".csv", sep = ""), row.names = FALSE, sep = ",")})
    

    这是R抛出的错误消息的顶部

    Error: Results must have one or more dimensions.
    In addition: Warning messages:
    1: In if (file == "") file <- stdout() else if (is.character(file)) { :
      the condition has length > 1 and only the first element will be used
    

    我错过了什么?

    3 回复  |  直到 9 年前
        1
  •  21
  •   IRTFM    15 年前

    试试这个:

    sapply(names(df.daily), 
     function (x) write.table(df.daily[[x]], file=paste(x, "txt", sep=".") )   )
    

    您应该会看到名称(“1”、“2”、“3”)一个接一个地弹出,但空值是写入磁盘文件的副作用已经完成的证据。(编辑:将[]更改为[[]]。)

        2
  •  8
  •   Marek    15 年前

    你可以用 mapply :

    mapply(
      write.table,
      x=df.daily, file=paste(names(df.daily), "txt", sep="."),
      MoreArgs=list(row.names=FALSE, sep=",")
    )
    

    thread about similar problem on plyr mailing list .

        3
  •  6
  •   Brandon Bertelsen    15 年前

    有几件事:

    laply 对列表执行操作。你要找的是 d_ply . 你不必在白天分手,你可以 plyr 为你这么做。另外,我不使用names(x),因为它返回data.frame的所有列名。

    d_ply(df, .(theday), function(x) write.csv(x, file=paste(x$theday,".csv",sep=""),row.names=F))