Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a text file to a list array?

Tags:

r

I just started coding in R-Lang and I was wondering what the best way to read a plan text file is? I am looking for something like this pseudo-code:

data = new List();
data = file.readall("myfile.txt")
close

foreach (a in data) {
  print(a)
}

pretty simple text, I read the tutorials but dont understand how R's file access works, it looks very much different to anything im used to.. I'm unsure what args to use.

like image 432
ace007 Avatar asked Dec 12 '22 18:12

ace007


2 Answers

Your pseudocode in R style:

dat = readLines("file.txt")

Now dat is a vector where each line in the file is an element in the vector. R is a functionally oriented language, so this performs a given function on each element:

l = lapply(dat, process_line)

Where process_line is the function that processes each line. The result is a list of processed lines. To put them into a data.frame:

do.call("rbind", l)

Or use ldply from the plyr package to do this in one go:

require(plyr)
ldply(dat, process_line)
like image 114
Paul Hiemstra Avatar answered Jan 04 '23 13:01

Paul Hiemstra


try this

  test.txt <- read.table("d:/test.txt", header=T)
like image 27
Rachel Gallen Avatar answered Jan 04 '23 12:01

Rachel Gallen