I have several text files (animal_grp1.txt, animal_grp2.txt...animal_grp50.txt) I want to import and modify in R by using a for loop.
I usually do this:
lote1 <- read.delim("animal_grp1.txt", header = T, sep = "\t")
lote1 <- lote1[c(2,5,7)]
names(lote1) <- c("ID", "race", "age")
but it is not efficient to repeat this code 50 times, so I was thinking that maybe by using a loop it would be more efficient.
Something like that:
animals <-c(1,2,3,4,5)
for(i in animal) {
lote[i] <- read.delim("animal_grp[i].txt", header = T, sep = "\t")
lote[i] <- lote[i][c(2,5,7)]
names(lote[i]) <- c("ID", "race", "age")
}
It seems it is not so simple as I thought. Any help?
Thanks
Sorry, I didn't see that you wanted to produce lote1, lote2, ... each as separate variables. If you do this it will cripple your work at a later stage - if it's inefficient to write 50 different lines of code to read in the data, it'll be just as inefficient to write 50 different lines to analyse the imported data. If you've got some large number of homogeneously structured files, and you're not up-to-speed with map/lapply in R, you'd be better constructing a list
lote <- vector(n = length(animals), mode = "list")
In the list
lote[[5]]
would return the value stored in the 5th element andlote[[7]] <- some_value
would storesome_value
in the 7th entry.So you could modify your code:
for (i in animals) { file_name <- paste0("animal_grp", i, ".txt") df <- read.delim(file_name, header = TRUE, sep = "\t")[c(2,5,7)] names(df) <- c("ID", "race", "age") lote[[i]] <- df }