我使用mapply函数“iter_group”。此函数返回3个值作为列表(我发现列表是在函数中返回多个值的最佳方法):
iter_group <- function(variable,index,time,status,tab){
... some calculations
# out <- list(cutoff,HR,PV) # <- this was the mistake
out <- c(cutoff,HR,PV) # <- gives the good dataframe output
return(out)
}
我遇到的问题是打印mapply返回的结果。在终端上,结果“res”很好地显示,但我没有设法打印它们。我尝试过数据帧转换,列表打印,unlist()。
res <-mapply(function(index{iter_group(variable,index,time,status,tab)}, iter_tab)
res <- as.data.frame(t(res))
colnames(res)<-c("cutoff", "HR", "Pvalue")
print(head(res))
print(typeof(res))
write.table(res, "outfile.csv", row.names = F, sep = "\t")
cutoff HR Pvalue
1 0 3.023552e-07 0.2724982
2 0 3.018152e-07 0.2179909
3 0 0.6458174 0.6601571
4 0 0.9644801 0.9609625
5 0 1.195378 0.7573982
6 0 1.037754 0.9477343
[1] "list"
Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol, :
type 'list' indisponible dans 'EncodeElement'
结果在终端上的格式非常好,但我们可以看到typeof(res)= list尽管有data.frame转换。
unlist(res) # does not solve the problem
res = as.data.frame(do.call(cbind, res)) # does not solve the problem
write(res, file="out.csv", sep = "\t") # does not print the results
lapply(res, write, "out.csv", append=TRUE, ncolumns=3) # does not print the results
感谢您的帮助!