Konrad Konrad - 19 days ago 5
R Question

Reading text file into a matrix honouring line breaks

Given is a text file of format

123
456
789


I would like to read this file into a matrix M resembling:

M <- matrix(data = c(1:9), nrow = 3, ncol = 3)


which gives:

>> str(M)
int [1:3, 1:3] 1 2 3 4 5 6 7 8 9


Initial attempt



impGrid <- readLines(con = "grid.txt")
lapply(X = strsplit(x = impGrid, split = ""), as.data.frame)


The
grid.txt
corresponds to a file of previously provided characteristics. So far this does not work, an alternative approach would involve working
readLines(con = "grid.txt")
vector converting it to a and breaking down strings of number into columns. At this junction it occurred to me that there must be a neater way of achieving the same result.

Answer

You can use read.fwf():

read.fwf("grid.txt", widths = c(1,1,1))

#  V1 V2 V3
#1  1  2  3
#2  4  5  6
#3  7  8  9