如何在R中将代码转换为更易读的形式

时间:2014-09-27 01:22:55

标签: 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 

前两行是命令,而后三行是输出。但是,这不能从这里复制回R终端,因为命令以'>开头。 &#39 ;.我怎样才能将其转换为:

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 "

但它无法粘贴到终端。

2 个答案:

答案 0 :(得分: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)在顶部附近,单击“源”按钮。它将在控制台中执行代码,这不是我们所追求的:相反,它会产生将代码保存到默认文件'〜/ .active-rstudio-document'的副作用。

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

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”)而不是单击“源”按钮来避免运行它两次。然后运行SO("xyz.R")

答案 1 :(得分:2)

您可以使用cat条件尝试ifelse

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中的一个规则是函数不能以_或数字开头。您可以根据自己的需要进行调整。