2017-09-01 123 views
1

我試圖爲每一行生成.pdf文檔,然後按照它們的行名稱存儲pdf文檔。下面是示例數據:爲每一行生成pdf文檔

canada <- c(100, 80, 100, 100, 20) 
korea <- c(100, 80, 100, 26, 65) 
brazil <- c(100, 90, 100, 30, 30) 
fruit <- rbind(canada, korea, brazil) 
colnames(fruit) <- c("apple", "orange", "banana", "grape", "kiwi") 
fruit 

price <- function(val){ 

    val <- tolower(val) 
    myrow <- fruit[val,] 
    nation <- tools::toTitleCase(val) 
    score.min <- c(myrow)[which.min(c(myrow))] 

    cat(paste0("In ", nation, " cheapest fruit costs ", score.min, " cents.")) 

} 

因此,對於輸出結果,我最終會得到三個pdf文檔:加拿大,韓國和巴西。而且,每個pdf文檔都會包含一句話:「在國家,最便宜的水果成本x美分。」

我到目前爲止已經嘗試過使用rmarkdown,但是我找不到一種方法來自動化按行名創建新PDF的過程。任何幫助將不勝感激。

回答

1

情節單線位編輯price。在price之下是在問題中定義的。沒有生成中間文件,也沒有使用包。這應該是最好的一個文本的頁面是足夠的,因爲你的問題只涉及每個文件一行。

write_lines_pdf(month.name) 

或者考慮使用gplots::textplot與地方的plot.new(); text(...)適當的參數:使用內置的矢量month.name

write_lines_pdf <- function(x, file = "pdffile", ...) { 
    if (!grepl("\\.pdf$", file)) file <- paste0(file, ".pdf") # append .pdf if not present 
    pdf(file) 
    plot.new() 
    text(x = 0, y = 1, labels = paste(x, collapse = "\n"), adj = c(0, 1), ...) 
    dev.off() 
} 

for(nm in rownames(fruit)) write_lines_pdf(capture.output(price(nm)), nm) 

另一個例子。

如果輸入字符串流出頁面一側,請嘗試strwrap以將文本打包到下一行或使用cex圖形參數縮小文本。如果x是輸入文本,則:

write_lines_pdf(strwrap(x, 50)) # wrap at column 50 

write_lines_pdf(x, cex = 0.7) # make text smaller 
+0

謝謝你的回答。這適用於我的腳本部分!我有另一個問題。對於長句來說,文本超出邊界而不是創建新行。一旦一個字即將跑出界限,我應該用什麼命令來告訴R創建一條新線? –

+1

如果'x'是您的輸入字符串,則使用'write_lines_pdf(strwrap(x,50))'將其包裝爲50個字符或'write_lines_pdf(x,cex = 0.5)'以使文本變小。根據需要改變50或0.5。如果你想使用'gplots :: textplot',它會自動設置'cex'。 –

+0

仍試圖找出它,但非常感謝你爲我提供的腳手架。我在講話時正在學習。 –

1

我不得不使用PDF格式的圖形驅動程序移除cat

price <- function(val){ 

    val <- tolower(val) 
    myrow <- fruit[val,] 
    nation <- tools::toTitleCase(val) 
    score.min <- c(myrow)[which.min(c(myrow))] 

    paste0("In ", nation, " cheapest fruit costs ", score.min, " cents.") 

} 

library(rmarkdown) 

for (x in rownames(fruit)) { 
    rmdfile = paste0(x,".Rmd") 
    cat(price(x), file=rmdfile) 
    render(input = rmdfile, output_format = "pdf_document") 
}