Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
拆分数据帧以在R中传递给sprintf_R_Dataframe_Printf_Lapply - Fatal编程技术网

拆分数据帧以在R中传递给sprintf

拆分数据帧以在R中传递给sprintf,r,dataframe,printf,lapply,R,Dataframe,Printf,Lapply,我有一个sprintf格式的字符串,我正试图通过它解析R中的数据帧。我构建了这段代码来实现它,但如果不是丑陋的话,那也没什么。有什么更好的方法可以做到这一点 writeData<-function(DataSet,FirstLine,FmtString,fName){ correctLine<-function (MyLine,FmtString){ do.call(sprintf,c(FmtString,MyLine)) } #why the

我有一个sprintf格式的字符串,我正试图通过它解析R中的数据帧。我构建了这段代码来实现它,但如果不是丑陋的话,那也没什么。有什么更好的方法可以做到这一点

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)
}
对比度:

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一次,并对所有列进行格式化。比如说

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

R中的大多数函数都是用来处理数据向量的,因此只需一次传入整个列,而不是遍历行。

实际数据帧的一部分dput会很有用。您是否尝试将格式应用于每一行?您最好执行按列转换。在R中,一次处理整个列几乎总是更好的。此外,询问是否有更好的方法来做到这一点也无济于事;最好描述一下你想要实现的目标。否则,我们必须尝试对您的代码进行反向工程,以了解您试图实现的目标。提供示例输入很好,但是您还应该告诉我们所需的输出是什么。只是好奇,为什么返回0?R不是C,在那里似乎没有必要。或者你真的想让它返回数字零?习惯的力量。这里肯定没用。你可以拿到绿色支票。效果很好。仅仅因为sprintf是C中的一个函数并不意味着我必须像对待C一样对待它。
writeData <- function(DataSet,FirstLine, FmtString,fName){
    outlines <- do.call("sprintf", c(FmtString, DataSet))
    writeLines(outLines,fName)
    return(0)
}