-4

I am trying to concatenate many vectors in R using c(). I have declared each of them to end with "_n" (i.e. filename_n). Now I want to know whether there is an easier method to read them all than just entering in each variable. I know in Bash I can use ls *.file_extension > filename to read all files in. Is there a similar method in R.

Thanks.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Concerned_Citizen
  • 6,548
  • 18
  • 57
  • 75
  • 5
    What do you mean by "datasets"? Does "abc_n" refer to the name of a variable in R and if so, what type is it (data frame? list? matrix?) Or does "abc_n" refer to a file on disk and if so, what format is it and how do you intend to read it into R (e.g. CSV -> data frame)? – neilfws Sep 06 '11 at 02:00
  • I mean vectors which I already declared. – Concerned_Citizen Sep 06 '11 at 03:39
  • It is helpful/encouraged for you to edit your question to clarify it, for the benefit of future readers, on the basis of the discussion in the comments below ... – Ben Bolker Sep 06 '11 at 12:31
  • 1
    @GTyler: Please read this http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and this http://www.catb.org/~esr/faqs/smart-questions.html – Richie Cotton Sep 06 '11 at 13:35

1 Answers1

5

From what I understand you might benefit from reading ?list.files, ?read.table, ?do.call, ?sapply. As a means of example,

files = list.files(pattern="*.txt", path = ".")
all = lapply(files, read.table, sep=",")
combined = do.call(c, all)

(untested)

EDIT: it looks like you're after ?ls and ?get now,

vars = lapply(ls(pattern = "_n"), get)
do.call(c, vars)

or, more succinctly,

sapply(ls(pattern = "_n"), get)
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • Indeed; my [answer](http://stackoverflow.com/questions/7311372/r-merging-data-from-many-files-and-plot-them/7311591#7311591) to a similar question earlier today might also be helpful. – joran Sep 06 '11 at 01:08
  • My datasets are already declared in R. Should I take out the path from list.files()? – Concerned_Citizen Sep 06 '11 at 01:43
  • I tried files<-list.files(pattern="*_n",path=".") but it's giving me character(0). – Concerned_Citizen Sep 06 '11 at 01:54
  • 2
    @GTyler - Your question is a bit misleading; at the end you seem to imply you're asking about how to load multiple data sets into R and then combine them. But your other comments suggest that you've already loaded them and just need to combine them. I think you should edit your question to clarify. – joran Sep 06 '11 at 02:10
  • +1 for list files. @GTyler: Your comparison with ls is misleading, because you state that your data is already "declared" in R. At least I am confused. – Matt Bannert Sep 06 '11 at 10:11
  • @ran2 I think he's trying to collect objects from workspace and concatenate them into one single variable. Baptiste showed how to get it done in his edited, second chunk using `do.call`. – Roman Luštrik Sep 06 '11 at 12:16