拆分数据帧以传递到R中的sprintf [英] Split Data Frame for passing to sprintf in R
本文介绍了拆分数据帧以传递到R中的sprintf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个sprintf格式的字符串,试图通过它解析R中的数据帧。我构建了此代码来做到这一点,但是如果不难看的话也算什么。有什么更好的方法?
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)
}
这里有一个例子:
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")
对比度:
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.
推荐答案
如果我了解您要正确执行的操作,您实际上只需要对所有列调用 sprintf
一次即可进行格式化。例如
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)
}
R中的大多数函数都旨在与数据向量一起使用,因此一次只传递整个列,而不是遍历行。
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.
这篇关于拆分数据帧以传递到R中的sprintf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文