Split Data Frame for passing to sprintf in R

谁说胖子不能爱 提交于 2019-12-24 03:00:38

问题


I have a sprintf format string that I'm trying to parse a dataframe in R through. I built this code to do it, but it is nothing if not ugly. What's a better way to do this?

writeData<-function(DataSet,FirstLine,FmtString,fName){
    correctLine<-function (MyLine,FmtString){
        do.call(sprintf,c(FmtString,MyLine))
    }
    #why the ugly split code? Because otherwise it casts my nice data frame as characters which confuses sprintf.
    outLines=lapply(split(DataSet,1:NROW(DataSet)),function (x){correctLine(x,FmtString)})
    writeLines(unlist(outLines),fName)
    return(0)
}

Here's an example:

z=data.frame(d1=c("A","B","C"),d2=c(1,2,3),d3=c("D","E","F"),stringsAsFactors=FALSE)
fmt="%s %0.3f %s"
writeData(z,"",fmt,"~/sample.txt")

Contrast:

correctLine<-function (MyLine,FmtString){do.call(sprintf,c(FmtString,MyLine))}
apply(z,1,function(x) {correctLine(x,fmt)}) #Errors out, wants a list
correctLine<-function (MyLine,FmtString){do.call(sprintf,as.list(c(FmtString,MyLine)))}
apply(z,1,function(x) {correctLine(x,fmt)}) # - still unhappy, now we have a character array. This is the problem.

回答1:


If I understand what you are trying to do correctly, you really only need to call sprintf once with all your columns to do the formatting. For example

writeData <- function(DataSet,FirstLine, FmtString,fName){
    outlines <- do.call("sprintf", c(FmtString, DataSet))
    writeLines(outLines,fName)
    return(0)
}

Most functions in R are meant to work with vectors of data so just pass in the entire column at a time rather than iterating over the rows.



来源:https://stackoverflow.com/questions/28058501/split-data-frame-for-passing-to-sprintf-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!