[R] 1. What function to use to read all the files in a directory to a vector in R code? 2. What function to use to coerce character string into numeric?

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Mon Nov 10 18:12:35 CET 2014


1. There is no built-in function to do that, but it can be done if you learn the basics of R [1]. For one thing, there is no assurance that all files in a directory will fit into vectors.. Most data fit better into data frames, and some data like XML need to be stored in lists of lists. So your first task is to work this out and use the str function to make sure you understand how your data for one file looks when imported into R variables.

Once you figure out how your files can be read in (perhaps with read.csv or read.table?) then you can use list.files to get a vector of filenames, and lapply to create a list of contents of files. You may need to re-read the discussions of lists and indexing in [1] again to see how to get the pieces out of the list. If all your files actually do have the same data frame structure, then you might find it useful to merge the list into a single data frame. Something like:

fnames <- list.files( pattern="\\.csv$" )
dtalist <- lapply(fnames,function(fn){read.csv(fn,stringsAsFactors=FALSE)})
alldta <- do.call(rbind,dtalist)

2. Read help file ?numeric.

You should also read the Posting Guide, which among other advice mentions that you should post using plain text format on this list rather than HTML (since we don't see what you see if you use the latter).

[1] Introduction to R, supplied with the software.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On November 10, 2014 5:12:10 AM PST, Aditya Singh <aps6dl at yahoo.com> wrote:
>Hi,
>I have 2 queries:
>1. What function to use to read all the files in a directory to a
>vector in R code?
>2. What function to use to coerce character string into numeric?
>As a help to others, I figured out to use setwd("C:/....") to set
>working directory!
>Aditya
>	[[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.



More information about the R-help mailing list