将粗略的R控制台输出转换为R文件
我正在尝试处理一个包含敏感数据的粗略文件,这意味着在r控制台中提供复制粘贴代码和r文件输出的地方无法发布真实版本,这看起来非常糟糕。基本上它看起来像这样,但是想象一下成千上万的线条将粗略的R控制台输出转换为R文件,r,R,我正在尝试处理一个包含敏感数据的粗略文件,这意味着在r控制台中提供复制粘贴代码和r文件输出的地方无法发布真实版本,这看起来非常糟糕。基本上它看起来像这样,但是想象一下成千上万的线条 > #here are some comments > > data(mtcars) > install.packages("dplyr") Installing package into �C:/Users/Home/Documents/R/win-library/3.6� (as �
> #here are some comments
>
> data(mtcars)
> install.packages("dplyr")
Installing package into �C:/Users/Home/Documents/R/win-library/3.6�
(as �lib� is unspecified)
trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.6/dplyr_0.8.5.zip'
Content type 'application/zip' length 3227917 bytes (3.1 MB)
downloaded 3.1 MB
package ‘dplyr’ successfully unpacked and MD5 sums checked
The downloaded binary packages are in
C:\Users\Home \AppData\Local\Temp\RtmpAnZJhs\downloaded_packages
>
>
> #let's look at some data
> dim(mtcars)
[1] 32 11
>
> #here is how to do a linear model
> lm(disp ~ mpg, data=mtcars)
Call:
lm(formula = disp ~ mpg, data = mtcars)
Coefficients:
(Intercept) mpg
580.88 -17.43
> summary(lm(disp ~ mpg, data=mtcars))
Call:
lm(formula = disp ~ mpg, data = mtcars)
Residuals:
Min 1Q Median 3Q Max
-103.05 -45.74 -8.17 46.65 153.75
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 580.884 41.740 13.917 1.26e-14 ***
mpg -17.429 1.993 -8.747 9.38e-10 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 66.86 on 30 degrees of freedom
Multiple R-squared: 0.7183, Adjusted R-squared: 0.709
F-statistic: 76.51 on 1 and 30 DF, p-value: 9.38e-10
此人没有旧的代码,但说在任何代码IDE中都有一种简单的方法来解决这个问题,但我认为Rstudio没有只读取带有>的部分并将其转换为R文件的功能。我试图将这个文件转换成python的文本文件,并逐行读取它,但这似乎没有真正起作用。我愿意采用任何一种解决方案,可以将这种混乱变成一个R文件,甚至是一个文本文件,可以复制粘贴到R中运行,而不需要所有糟糕的控制台输出您可以尝试下面的方法,在给定的输入下,我已经编写了代码,将整个代码文本保存在一个名为text.txt的文件中,然后执行以下操作
rd <- readLines('text.txt')
code_part <- grep('^>.+$', rd, value=TRUE)
code_part <- trimws(gsub('^>', '', code_part))
writeLines(paste(code_part, collapse = '\n'), 'file.txt')
您可以在下面的appraoch中尝试,在给定的输入下,我已经编写了代码,将整个代码文本保存在一个名为text.txt的文件中,然后执行以下操作
rd <- readLines('text.txt')
code_part <- grep('^>.+$', rd, value=TRUE)
code_part <- trimws(gsub('^>', '', code_part))
writeLines(paste(code_part, collapse = '\n'), 'file.txt')