mathkid mathkid - 2 months ago 24
R Question

Importing and processing a text file

I have a text file (myfile.txt) which looks as follows,

Subject: 5581 2005 471791 80 15184 64 2155 5581 2005 80 21292 10607 47 64 209 22910 132 1672 84 3865 84 1570 84 2005 84 10492 1847 12330 4797 82 13886 2170 47

What I want is a vector A such that it's elements will be as follows

A[1]=5581 A[2]=2005 A[3]=471791 ..... and so on

I tried read.table() and readLines() which didn't help. Any help will be appreciated.

Answer

We can use scan to read the file to create a vector of class numeric

A <- scan("myfile.txt", what = numeric(), quiet=TRUE)

If there is also the Subject: as prefix in the beginning, we read the file with readLines, remove the prefix part with sub, and read it with scan

lines <- readLines("myfile.txt")
A <- scan(text= paste(sub("^\\S+\\s+", "", lines), collapse=" "),
                      what = numeric(), quiet=TRUE)
Comments