如何在R中读取以空格分隔的字符串直到EOF



我是R的新手,在遇到EOF之前,我目前无法读取一系列字符串。我不仅不知道如何检测EOF,而且也不知道如何读取由空格分隔的单个字符串,这在我迄今为止见过的任何其他语言中都是微不足道的。在C中,我会简单地做:

while (scanf("%s", s) == 1) { /* do something with s */ }

如果可能的话,我更喜欢一种不需要事先知道字符串的最大长度的解决方案。

有什么想法吗?

编辑:我正在寻找一种解决方案,它不将所有输入存储到内存中,而是与上面的C代码等效或至少类似的解决方案。

这里有一种一次读取一项的方法。。。它使用了scan有一个nmax参数的事实(以及nnlines——实际上有点乱!(。

# First create a sample file to read from...
writeLines(c("Hello world", "and now", "Goodbye"), "foo.txt")
# Use a file connection to read from...
f <- file("foo.txt", "r")
i <- 0L
repeat {
   s <- scan(f, "", nmax=1, quiet=TRUE)
   if (length(s) == 0) break
   i <- i + 1L
   cat("Read item #", i, ": ", s, "n", sep="")
}
close(f)

当扫描遇到EOF时,它返回一个零长度矢量。因此,一种更模糊但类似C的方式是:

while (length(s <- scan(f, "", nmax=1, quiet=TRUE))) {
   i <- i + 1L
   cat("Read item #", i, ": ", s, "n", sep="")
}

在任何情况下,输出都是:

Read item #1: Hello
Read item #2: world
Read item #3: and
Read item #4: now
Read item #5: Goodbye

最后,如果您可以向量化对字符串所做的操作,那么您可能应该尝试一次读取一堆字符串——只需将nmax更改为10000即可。

> txt <- "This is an example"  # could be from a file but will use textConnection()
> read.table(textConnection(txt))
    V1 V2 V3      V4
1 This is an example

read.table是用scan实现的,所以您只需查看代码即可了解专家是如何做到的。

最新更新