简体   繁体   中英

How to call a variable using a vector and for loop in R

I'm trying to be efficient and use a loop instead of copy-pasting code. I would also like to limit my hard-coding of ID numbers.

I want to loop through a vector containing ID numbers to open and name various data sets with lapply. Here is what I can do via copy-paste to get what I need:

id2174 <- lapply(trials_2174, 
                        FUN = read.table,
                        header = FALSE,
                        sep=",")

id2181 <- lapply(trials_2181, 
                        FUN = read.table,
                        header = FALSE,
                        sep=",")

id2182 <- lapply(trials_2182, 
                        FUN = read.table,
                        header = FALSE,
                        sep=",")

I have a variable named id_nums containing the IDs: 2174, 2181, 2182, 2183, 2185, etc. How do I iterate through these IDs and apply them to the vector argument in lapply, while maintaining the necessary "trials_" part of the vector name? So that it reads like the copy-pasted formula above?

Below is what I've tried, with various changes (single bracket, +, "trials_", etc.) with no success:

EDIT: The trials_2174, trials_2181, etc. variables are file directories. I had used list.files to compile them. Ultimately I need 5 lists of data frames for each ID, not a single list of data frames.

for (i in id_nums) {
  assign(paste0("id",i), lapply(trials_[[i]],
                                 FUN = read.table,
                                 header = FALSE,
                                 sep = ","))
}

It seems like such a simple syntax thing, but I haven't been able to find anything that works. Let me know if I can somehow clarify my question! Thanks!

Maybe this serves your purpose:

idnum <- c(2174, 2181, 2182, 2183, 2185)

# To create "trials_2174", "trials_2181", etc:
trials <- paste0("trials_", idnum)

# Prepare an empty list to contain the result of read.table later.
# The number of elements of this list equals the length of idnum.
ids <- vector("list", length(idnum))

#Apply `read.table` to trials2174, trials 2181, etc, and 
# store the results in the ids list. 

ids <- lapply(trials, read.table, header = FALSE, sep=",")
names(ids) <-paste0("id", idnum)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM