简体   繁体   中英

Write a R function with varied number of input files

I would write a local R function with varied number of input files such as:

test<-function(file1, file2, ...){
     dat1<-read.table(file1)
     dat2<-read.table(file2)
     ....
     dat<-cbind.data.frame(dat1, dat2, ...)
   return(dat)
}

Since the input files could be varied from 1 to as many as a local customer want, I would like to know how to realize it in R.

Here is a little example to compute factorials from a list of numbers ... You don't have to give the starting elements.

test<-function( ...){
  lapply(list(...), factorial)
}
test(1:10)

[[1]]
[1]       1       2       6      24     120     720    5040   40320

[9]  362880 3628800

Try the following:

test <- function(...) {
    files <- list(...);
    data <- lapply(files, read.table);
    return(do.call(cbind, data));
}

How about using lapply and do.call :

your_files = c('a.txt', 'b.txt')
do.call(what = 'cbind', args = lapply(your_files, read.table))

just wrap that into a function and you are done

A bit more elegant with magrittr:

library(magrittr)
test <- function(...){
    list(...) %>%
        lapply(read.table) %>%
        do.call(cbind, .)
}

PS: Actually, I'd recommend you to write it in a way that input file names come as a single vector. It may benefit further. Something like this:

test <- function(x){
    lapply(x, read.table) %>% do.call(cbind, .)
}

Where x looks like c("file1", "file2", ...) . Then if you, for example, want to read and bind all the tables in a folder, you can simply do

data <- list.files("dir", full.names = TRUE) %>% test()

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