2015-11-05 44 views
0

我試圖動態地構建一個html文件,其中一個變量將取決於匹配模式的目錄中的文件數量。下面是代碼:當使用sprintf獲取無效格式響應時 - 無效格式'%he'

html <- ' 
<!DOCTYPE HTML> 
<html> 
    <head> 
    <meta charset = "utf-8"> 
    <title>Sankey Plot Test</title> 
    <script type = "text/javascript" src = "http://code.jquery.com/jquery-latest.min.js"></script> 
    </head> 

    <body> 
    <iframe src = "plot0.html" width = 100% height = 1000px id = "sankey" style = "border: none"></iframe> 
    <script> 
     $(function() { 
     var selector = $("#sankey"); 
     var delay_sec = 1; 
     var num = 1, 
      len = %d; 
     setInterval(function() { 
      num = (num === len) ? 0 : num; 
      selector.attr("src", "plot" + num + ".html"); 
      num++; 
     }, delay_sec * 1000); 
     }); 
    </script> 
    </body> 
</html>' 
n <- list.files(path = "path/to/files", pattern = "plot\\d+.html") %>% length() 
html <- sprintf(html, n) 

它返回一個錯誤,指出該格式不正確我的整數對象,儘管使用%d。我在SO上看到一些其他的問題,提到使用%dsprintf時出現錯誤的格式錯誤,但沒有一個像我所看到的。

任何有關正在發生的事情的深入瞭解將不勝感激。謝謝!

+0

這是因爲它將'%he'作爲'width = 100%height = 1000px'的一部分 - 這可能是由您代表一些非常基本的調試識別出來的。開始逐行刪除「html」文本,直到找到引入錯誤的時間。 – thelatemail

+0

你們兩個都是天才。謝謝!我可以使用'stringr :: str_interp'來代替。 – brittenb

+1

順便說一下,XML包具有更改html節點和屬性的功能。我認爲這將是更安全的路線,而不是做字符串解析的東西。 –

回答

4

您的問題是在這條線:

<iframe src = "plot0.html" width = 100% height 

通知的%。你可以用這樣的另一個%轉義%:

<iframe src = "plot0.html" width = 100%% height 

當sprintf的貫穿串它將輸出100%正確。