gpt4 book ai didi

r - 如何在 R 中将代码转换为更具可读性的形式

转载 作者:行者123 更新时间:2023-12-04 10:34:59 24 4
gpt4 key购买 nike

我从终端复制代码在这里发布。它的形式如下:

> 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

前 2 行是命令,而后 3 行是输出。但是,由于命令以“>”开头,因此无法从此处将其复制回 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 "

但它无法粘贴到终端。

最佳答案

我一直在等待机会分享我保存在我的 .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()从控制台(左下象限)从保存的文件中获取代码(再次......),捕获输出并以非常友好的格式打印它:
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") .

关于r - 如何在 R 中将代码转换为更具可读性的形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26070388/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com