Reputation: 317
Hi create a list file in R and then I saved it using write.table()
to file.txt.
Now, I would like to import the file.txt in R but I have problems doing that.
The list in the file.txt is like this (opening it with Notes of Windows).
"1" c(133, 292, 460, 603, 762, 929, 1027, 1060, 1199, 1373, 1523, 1698, 1875)
"2" c(145, 322, 475, 654, 790, 922, 1085, 1251, 1411, 1451, 1562, 1737, 1861)
"3" c(142, 308, 370, 473, 612, 765, 920, 1096, 1225, 1374, 1501, 1640, 1771, 1878)
"4" c(146, 324, 389, 464, 611, 748, 914, 1048, 1203, 1338, 1499, 1672, 1823)
"5" c(146, 287, 329, 482, 659, 815, 843, 980, 1157, 1315, 1450, 1585, 1756, 1866, 1898)
"6" c(133, 259, 443, 590, 772, 917, 996, 1059, 1081, 1206, 1365, 1523, 1690, 1845)
I have tried to use read.table()
but it replies with an Error.
How can I import the file and read all the lines?
Upvotes: 0
Views: 191
Reputation: 38500
Here is a way to parse this into a list of integers. You would benefit in the future by using save
and load
in the future.
# read in file
myList <- gsub("(^.*\\ c\\(|\\)$)", "", readLines("<path>/<fileName>"))
# get integer list
myList <- lapply(strsplit(myList, split=", "), as.integer)
The readLines
function reads in each line as a string and returns a character vector and gsub
strips out "c(" and ")". This is then fed to strsplit
which splits on the " ," and returns a list of character vectors which is fed to lapply
which converts these vectors into integers with as.integer
.
Upvotes: 1
Reputation: 13274
You could also use a combination of parse
,eval
and cbind
:
text_data <- readLines(file("file.txt"))
theoutput <- do.call(cbind,lapply(gsub(".*(?=c)","",text_data,perl = T), function(x) {
eval(parse(text=x))
}))
Upvotes: 0