[R] how to process multiple data files using R loop

Greg Snow 538280 at gmail.com
Mon Aug 11 18:04:58 CEST 2014


In addition to the solution and comments that you have already
received, here are a couple of additional comments:

This is a variant on FAQ 7.21, if you had found that FAQ then it would
have told you about the get function.

The most important part of the answer in FAQ 7.21 is the last part
where it says that it is better to use a list.  If all the objects of
interest are related and you want to do the same or similar things to
each one, then having them all stored in a single list can simplify
things for the future.  You can collect all the objects into a single
list using the mget command, e.g.:

P_objects <- mget( ls(pattern='P_'))

Now that they are in a list you can do the equivalent of your loop,
but simpler with the lapply function, e.g.:

lapply( P_objects, head, 2 )

And if you want to do other things with all these objects, such as
save them, plot them, do a regression analysis on them, delete them,
etc. then you can do that using lapply/sapply as well in a simpler way
than looping.


On Fri, Aug 8, 2014 at 12:25 PM, Fix Ace <acefix at rocketmail.com> wrote:
> I have 16 files and would like to check the information of their first two lines, what I did:
>
>
>> ls(pattern="P_")
>  [1] "P_3_utr_source_data"               "P_5_utr_source_data"
>  [3] "P_exon_per_gene_cds_source_data"   "P_exon_per_gene_source_data"
>  [5] "P_exon_source_data"                "P_first_exon_oncds_source_data"
>  [7] "P_first_intron_oncds_source_data"  "P_first_intron_ongene_source_data"
>  [9] "P_firt_exon_ongene_source_data"    "P_gene_cds_source_data"
> [11] "P_gene_source_data"                "P_intron_source_data"
> [13] "P_last_exon_oncds_source_data"     "P_last_exon_ongene_source_data"
> [15] "P_last_intron_oncds_source_data"   "P_last_intron_ongene_source_data"
>
>
>
>>for(i in ls(pattern="P_")){head(i, 2)}
>
> It obviously does not work since nothing came out
>
> What I would like to see for the output is :
>
>> head(P_3_utr_source_data,2)
>   V1
> 1  1
> 2  1
>> head(P_5_utr_source_data,2)
>   V1
> 1  1
> 2  1
>>
> .
>
> .
> .
>
>
>
> Could anybody help me with this?
>
> Thank you very much for your time:)
>         [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Gregory (Greg) L. Snow Ph.D.
538280 at gmail.com



More information about the R-help mailing list