我正在读取文件,其中每一行中都有用空格分隔的数字。
我正在使用以下命令
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.
是否有任何不使用任何外部库的最佳方法?
如果文件内容与其发布的说明相匹配,scan
将自动读取数字。
f <- file('test.txt', open = 'rt')
x <- scan(f)
阅读9个项目
close(f)
x
#[1] 1 2 3 4 5 6 7 8 9
文件test.txt
。
该文件是Ubuntu 19.10文本文件,行以'\n'
结尾。数字由空格分隔,不一定是一个空格。
1 2 3 4
5 6
7 8 9
请注意,这也适用于非整数。我已经编辑了上面的文件以包含数字3.14
。
f <- file('test2.txt', open = 'rt')
x <- scan(f)
阅读9个项目
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
一般来说,如果输入CSV中的每一行包含相同数量的字词,那么您可以只使用read.csv
:
f <- "path/to/your/input.csv"
T1 <- read.csv(file=f, sep=" ") # using space as a separator
如果每行可以包含可变数量的数字,那么您当前的方法是可以接受的。