ace007
ace007

Reputation: 577

How to read a text file to a list array?

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.

Upvotes: 4

Views: 21832

Answers (2)

Paul Hiemstra
Paul Hiemstra

Reputation: 60984

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)

Upvotes: 7

Rachel Gallen
Rachel Gallen

Reputation: 28583

try this

  test.txt <- read.table("d:/test.txt", header=T)

Upvotes: 6

Related Questions