右 |阅读线 |读取仅包含数字的文件(以空格分隔)

R | readLine | read file containing numbers only (separated by whitespace)

我正在读取一个文件,其中每一行都有用空格分隔的数字。

我正在使用以下命令

f <- file("stdin")

on.exit(close(f))

L <- strsplit(readLines(f), "\n")

T1 <- as.numeric(unlist(strsplit(L[[1]], split = "\s"))) # to read line containing numbers separated by spaces.

有没有不使用任何外部库的最佳方法?

通常,如果输入的 CSV 中的每一行都包含相同数量的术语,那么您可以只使用 read.csv:

f <- "path/to/your/input.csv"
T1 <- read.csv(file=f, sep=" ")  # using space as a separator

如果每一行都可以包含可变数量的数字,那么您当前的方法是可以接受的。

如果文件内容与其发布的描述相符,scan 将自动读入数字。

f <- file('test.txt', open = 'rt')
x <- scan(f)

Read 9 items

close(f)

x
#[1] 1 2 3 4 5 6 7 8 9

文件 test.txt.

该文件是一个 Ubuntu 19.10 文本文件,行以 '\n' 结尾。数字由 space 分隔,不一定只有一个 space.

1 2 3 4
5 6 
7  8 9

编辑

请注意,这也适用于非整数。我已经编辑了上面的文件以包含一个数字 3.14.

f <- file('test2.txt', open = 'rt')
x <- scan(f)

Read 9 items

close(f)

x
#[1] 1.00 2.00 3.14 4.00 5.00 6.00 7.00 8.00 9.00

文件 test2.txt.

1 2 3.14 4
5 6 
7  8 9