如何将R语言代码转换成更易读的形式?

5
我从终端复制代码到这里发布。它的格式如下:
> ddf2 = ddf[ddf$stone_ny>'stone',] # this is first command
> ddf2[!duplicated(ddf2$deltnr),]   # second command
   deltnr us stone_ny stone_mobility      
4    1536 63    stone         mobile 
10   1336 62    stone         mobile 

前两行是命令,而接下来的三行是输出结果。然而,由于命令是以"> "开始的,因此无法将其从此处复制回R终端。您应该如何转换为:
ddf2 = ddf[ddf$stone_ny>'stone',] # this is first command
ddf2[!duplicated(ddf2$deltnr),]   # second command
#   deltnr us stone_ny stone_mobility      
#4    1536 63    stone         mobile 
#10   1336 62    stone         mobile 

所以它变得适合从这里复制。
我尝试了:
text
[1] "> ddf2 = ddf[ddf$stone_ny>'stone',] # this is first command\n> ddf2[!duplicated(ddf2$deltnr),]   # second command\n   deltnr us stone_ny stone_mobility      \n4    1536 63    stone         mobile \n10   1336 62    stone         mobile "


text2 = gsub('\n','#',text)
text2 = gsub('#>','\n',text2)
text2 = gsub('#','\n#',text2)
text2
[1] "> ddf2 = ddf[ddf$stone_ny>'stone',] \n# this is first command\n 
ddf2[!duplicated(ddf2$deltnr),]   \n# second command\n#   deltnr us stone_ny stone_mobility      \n#4    1536 63    stone         mobile \n#10   1336 62    stone         mobile "

但它无法粘贴到终端。

如果您正在使用RStudio,您可以在脚本编辑器区域轻松编写代码,并使用Ctrl + Alt + C注释结果。 - A5C1D2H2I1M1N2O1R2T1
我的系统(Linux Debian stable上的R studio 0.98.501)中Ctrl+Alt+C无法使用。 - rnso
另外,您可能想看看 Sublime Text 3 + Enhanced R package(适用于ST3)。多行编辑功能非常强大。 - Ricardo Saporta
我认为实际上是 Ctrl + Shift + C,或者使用菜单 Code > Comment / Uncomment Lines。 - Gregor Thomas
如果您在Windows上使用常规的Rgui界面来运行R,则将代码与>标记一起复制到剪贴板中,然后在Rgui中选择“编辑”,然后选择“仅粘贴命令”。请注意,许多在SO上发布其代码的人会在输出行前面添加##标记,并且不包括> - G. Grothendieck
2个回答

7

我一直在等待机会分享我在.Rprofile文件中保存的这个函数。虽然它可能不完全回答你的问题,但我觉得它实现了非常接近你想要的东西。所以你可以通过查看它的代码来获取一些想法。其他人可能会发现它就是有用的。该函数:

SO <- function(script.file = '~/.active-rstudio-document') {

   # run the code and store the output in a character vector
   tmp <- tempfile()
   capture.output(
      source(script.file, echo = TRUE, 
                          prompt.echo = "> ",
                          continue.echo = "+ "), file = tmp)
   out <- readLines(tmp)

   # identify lines that are comments, code, results
   idx.comments <- grep("^> [#]{2}", out)
   idx.code     <- grep("^[>+] ", out)
   idx.blank    <- grep("^[[:space:]]*$", out)
   idx.results  <- setdiff(seq_along(out),
                           c(idx.comments, idx.code, idx.blank))
   # reformat
   out[idx.comments] <- sub("^> [#]{2} ", "", out[idx.comments])
   out[idx.code]     <- sub("^[>+] ", "    ", out[idx.code])
   out[idx.results]  <- sub("^", "    # ", out[idx.results])

   # output
   cat(out, sep = "\n", file = stdout())
}

这个SO函数是我在StackOverflow网站上快速格式化答案的工具。我的工作流程如下:

1)在RStudio中,在一个无标题的脚本中编写我的答案(即左上角的区域)。例如:

## This is super easy, you can do

set.seed(123)
# initialize x
x <- 0
while(x < 0.5) {
   print(x)
   # update x
   x <- runif(1)
}

## And voila.

2) 在页面顶部附近,单击“Source”按钮。这将在控制台中执行代码,但这并不是我们想要的:实际上,它会产生副作用,将代码保存到默认文件“~ / .active-rstudio-document”。

3) 从控制台(左下方)运行 SO(),它将从保存的文件中再次获取代码,捕获输出并以SO友好的格式进行打印:

This is super easy, you can do

    set.seed(123)
    # initialize x
    x <- 0
    while(x < 0.5) {
       print(x)
       # update x
       x <- runif(1)
    }
    # [1] 0
    # [1] 0.2875775

And voila.

4) 将代码复制粘贴到stackoverflow,然后完成。

注:对于运行时间较长的代码,您可以将脚本保存到文件中(例如“xyz.R”),而不是点击“Source”按钮。然后运行SO("xyz.R")


好的,正如你所看到的,当我重新格式化时,我假设提示符是“>”。因此,我可以使用默认的prompt.echo = getOption("prompt")调用source,但我需要在我的正则表达式中使用getOption("prompt"),或者通过在源调用中添加prompt.echo = "> "来强制使用"> "。我选择了后者,请查看我的编辑。 - flodel
我最好奇的是你是否用你的函数产生了整个答案。 :) - Rich Scriven
我们需要更深入! - flodel
@flodel:很棒的函数。理想情况下,它应该被整合到stackoverflow网页中,这样文本就可以直接从R终端粘贴到stackoverflow上了。 - rnso
@rnso,已经完成了一半......如何将内容粘贴到文本框中?http://bit.ly/so_functions - Ricardo Saporta
显示剩余2条评论

2
你可以尝试在一个ifelse条件下使用cat。
cat(ifelse(substr(s <- strsplit(text, "\n")[[1]], 1, 1) %in% c("_", 0:9, " "), 
           paste0("# ", s), 
           gsub("[>] ", "", s)), 
    sep = "\n")

这会导致
ddf2 = ddf[ddf$stone_ny>'stone',] # this is first command
ddf2[!duplicated(ddf2$deltnr),]   # second command
#    deltnr us stone_ny stone_mobility      
# 4    1536 63    stone         mobile 
# 10   1336 62    stone         mobile 

"_"0:9是因为R语言的规则之一是函数不能以_或数字开头。您可以根据需要进行调整。


它可以工作。我也会尝试复制自终端的其他文本。 - rnso
@rnso - cat 还有 labelsfill 参数,可能会派上用场。例如:cat(paste(letters, 10* 1:15), fill = TRUE, labels = paste0("{", 1:15, "}:")) - Rich Scriven
我从来没有去关注cat命令中的其他参数。每天都有新的东西可以学习! - Ricardo Saporta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接