问题
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