在R Studio中使用stdin [英] Use stdin from within R studio
问题描述
当我尝试以下操作时:
f<-file("stdin")
lines<-readLines(f)
在Ubuntu上的R-studio中,
我可以输入文本,但是无法终止它. Ctr + C/D,随机敲击键盘无济于事.它只是挂起
from within R-studio on Ubuntu I can input text but unable to terminate it. Ctr+C/D, random hitting keyboard won't help. It simply hangs
到目前为止,我只发现了追随者 如何在R中的stdin中输入EOF? 但那里没有帮助-必须杀死R-studio.
I only found the followin so far How to input EOF in stdin in R? but no help there - had to kill R-studio.
有人解释出什么问题了吗
Anybody have explanation what is wrong?
推荐答案
大概是Rstudio重定向了stdin,因此无法再以"stdin"
或"/dev/stdin"
的形式正确访问它.但是,stdin()
仍然有效.
Presumably, Rstudio is redirecting stdin, so that it cannot be properly accessed as "stdin"
or "/dev/stdin"
any longer. However, stdin()
still works.
我仍然无法真正键入Ctrl + D.但是可以读取固定数量的行:
I was still unable to actually type Ctrl+D. But it is possible to read a fixed number of lines:
> a <- readLines(stdin(), n=2)
Hello
World
> a
[1] "Hello" "World"
我还发现了一种可以帮助进行交互式调试的hack.假设您的手动示例中最多有10行.然后,您可以
I've also discovered a hack that may help for interactive debugging. Let's say, you have at most 10 lines in your manual examples. Then you can do
> a <- readLines(stdin(), n=10)
abc
def
ghi
# and now just keep pressing ENTER
...
> a <- a[a != ""]
> a
[1] "abc" "def" "ghi"
如果您在可以使用Ctrl + D的环境中运行相同的代码,它也会正确终止输入.
If you run the same code in an environment where Ctrl+D is available, it also properly terminates the input.
注意事项:但stdin()
不适用于Rscript
:您必须切换回file("stdin")
.此外,在某些环境中,如果将readLines
与n=1
结合使用以逐行读取文件,则最终可能会重新打开文件并每次都获得第一行.似乎将所有内容都放入一个文件中并使用例如一次读取整个文件read.table
是使用Rstudio开发的一种更强大的方法.
Caveats: but stdin()
does not work with Rscript
: you'd have to switch back to file("stdin")
. Furthermore, in some environments, if you use readLines
with n=1
to read the file line-by-line, you may end up reopening the file and getting the first line every time. It seems that putting everything into a file and reading the whole file at once with e.g. read.table
is a much more robust way of developing with Rstudio.
这篇关于在R Studio中使用stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!