问题 如何在roxygen literate编程中逃脱%?


我的函数的参数的默认值包含“%”。这似乎是roxygen的一个问题,它会产生很多警告,并且在尝试构建乳胶文档时R CMD检查失败。

如何使此功能(及其文档)有效?使用%%或\%代替%无济于事。

#' Test escape \% from in-source documentation (roxygen).
#'
#' What happens when parameters contain special latex characters? 
#'
#' @param x unsuspicious parameter 
#' @param format sprintf format string (default "\%5.0f")
#'
#' @return formatted string
#' @export
#' @author Karsten Weinert
testroxy <- function(x, format = "%5.0f") {
  sprintf(format,x)
}

9267
2018-04-02 10:21


起源

是的,我试过了两个。我纠正了上面的代码片段。 - Karsten W.
您是否直接通过电子邮件发送给开发据我所知,像大多数R开发人员一样,他们不会在堆栈溢出时闲逛 - hadley
不,我没有,我认为这是一个用户错误。现在我加入了roxygen邮件列表并重新发布了问题。 - Karsten W.
如果你有答案,请在这里发布答案。 - Shane


答案:


#!/usr/bin/perl
use strict;
use File::Temp qw/tempfile/;
use File::Copy;

my $usage = <<EOD

  $0 file1.Rd [file2.Rd ...]

  When using roxygen to generate documentation for an R pacakge, if a default
  argument has a percent sign in it then roxygen will copy it directly into
  the .Rd file. Since .Rd is basically latex, this will be interpreted as a
  comment and case the file to be parsed incorrectly.

  For percent signs elsewhere in your documentation, for example in the
  description of one of the parameters, you should use "\%" so parse_Rd
  interprets it correctly.

  But you cannot do this in the default arguments because they have to be
  valid R code, too.

  Since the .Rd files are automatically generated they should not have
  any latex comments in them anyway.

  This script escapes every unescaped % within the file.

  The .Rd files are modified in place, since it would be easy to
  generate them again with R CMD roxygen.

EOD
;

my $n_tot = 0;
my $n_file = @ARGV;
my $n_esc_file = 0;
foreach my $fn (@ARGV)  {

  print STDERR ' ' x 100, "\rWorking on $fn\t";
  open my $fh, $fn or die "Couldn't open $fn: $!";
  my ($tmp_fh, $tmp_fn) = tempfile();

  my $n;
  while(<$fh>)  {
    $n += s/(?<!\\)%/\\%/g;  # if % is not preceded with backslash then replace it with '\%'
    print $tmp_fh $_;
  }
  $n_tot += $n;
  $n_esc_file ++ if $n;
  print "Escaped $n '%'\n" if $n;
  close $tmp_fh;
  move($tmp_fn => $fn);
}

print "\n";

print "$n_file files parsed\n";
print "$n_esc_file contained at least one unescaped %\n";
print "$n_tot total % were escaped\n";

这是我不优雅的解决方案。将perl脚本保存为例如escape_percents.pl,然后序列将如下所示:

R CMD roxygen my.package
perl escape_percents.pl my.package.roxygen/man/*.Rd
R CMD install my.package.roxygen

这可能会引入更多问题,例如,如果您使用%%作为模数运算符的示例代码,但它对我来说非常方便。


6
2017-12-22 21:54



或者使用roxygen2 - hadley
然后做什么? - tim
@tim in roxygen 2你可以使用\%来逃避百分号 - JTextor


类似于问题中的代码对我没有问题,并生成正确的文档。正如多条评论所说,原因必须是我正在使用roxygen2包。所以只需使用roxygen2然后使用反斜杠在文档中转义“%”:

#' The percentage sign is written in the documentation like this: \%.

5
2018-06-22 11:42



运用 roxygen2 我相信? - SymbolixAU
是的,你必须是正确的,这一定是原因。我刚刚安装了RStudio,并使用了随附的任何东西。我会相应地改变我的答案。谢谢! - jciloa