Skip to content
Prev 343052 / 398506 Next

how to process multiple data files using R loop

Thank you very much for all replies:) Here is my working code:

for(i in ls(pattern="P_")){print(head(get(i),2))}
On Monday, August 11, 2014 11:04 AM, Greg Snow <538280 at gmail.com> wrote:
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: