Gaurav Chavan
Gaurav Chavan

Reputation: 63

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

I am reading a file where in each line there are numbers separated by spaces.

I am using following command

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.

Is there any optimal way to do without using any external libraries ?

Upvotes: 0

Views: 374

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76402

If the file contents matches its posted description, scan will read in numbers automatically.

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

File test.txt.

The file is a Ubuntu 19.10 text file, lines end with '\n'. Numbers are separated by spaces, not necessarily just one space.

1 2 3 4
5 6 
7  8 9

Edit

Note that this also works with non integers. I have edited the file above to include a number 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

File test2.txt.

1 2 3.14 4
5 6 
7  8 9

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521209

Trivially, if each line in your input CSV contain the same number of terms, then you may just use read.csv:

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

If each line could contain a variable count of numbers, then your current approach is acceptable.

Upvotes: 1

Related Questions