[R] Using changing names in loop in R
Joshua Wiley
jwiley.psych at gmail.com
Sun Nov 7 01:15:44 CET 2010
On Sat, Nov 6, 2010 at 3:13 PM, Tuatara <franziskabroell at gmail.com> wrote:
>
> A more detailed example:
>
> Say I would like to read in data files that are set-up identically and have
> identical (but somewhat) different text names (see below):
>
> data_1 <- read.csv("data1.txt")
> data_2 <- read.csv("data2.txt")
> data_3 <- read.csv("data3.txt")
>
> How do I automate this process?
Well, the (nearly) verbatim automated duplicate would be:
for(i in 1:3) {
assign(x = paste("data", i, sep = "_"), value =
read.csv(paste("data", i, ".txt", sep = '')))
}
but the preferred way would be:
dat <- lapply(1:3, function(x) {read.csv(paste("data", x, ".txt", sep = ''))})
which would read in and store all three files in one convenient list.
Josh
>
> (I assume the way I make R understand that the data file extension is to be
> read as a number rather than a string is the same for things like applying
> functions to matrices with different extensions, e.g. data_i, i = 1,2,3)
> --
> View this message in context: http://r.789695.n4.nabble.com/Using-changing-names-in-loop-in-R-tp3030132p3030412.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/
More information about the R-help
mailing list