简体   繁体   English

读取同一表中R中的多个文件,作为不同的变量

[英]Reading in multiple files in R in the same table, as different variables

I have 100 files, each named rundataX, where x is the number. 我有100个文件,每个文件名为rundataX,其中x是数字。 I want to read them in in R in one table called mydata. 我想在R中的一个名为mydata的表中读取它们。 Each of the rundata files has 3 columns: tmX , scoreX and currentX . 每个rundata文件都有3列: tmXscoreXcurrentX I can read in one file like this: 我可以像这样读取一个文件:

mydata = read.table("rundata1", sep= " ", 
                    col.names=c("tm1","score1","current1"))

If I read in the next file, it the previous variables seem to disappear: 如果我读下一个文件,以前的变量似乎消失了:

mydata = read.table("rundata2", sep= " ", 
                    col.names=c("tm2","score2","current2"))

Is there some option that allows me to "append" columns (and thus variables). 是否有一些选项可以让我“附加”列(以及变量)。 Note that they do all have different lengths (number of rows). 请注意,它们的长度(行数)都不同。 Most of the posts I find here are on multiple files for splitting up rows, not columns. 我在这里找到的大多数帖子都位于多个文件中,用于拆分行而不是列。

Here's way with list.files and lapply : 这就是list.fileslapply的方式:

filenames <- list.files(pattern = "^rundata\\d+$")
dat       <- do.call(rbind, lapply(filenames, read.table, sep = " ", 
                                   col.names = c("tm", "score", "current")))

In your code, you overwrite mydata each time you use read.table . 在代码中,每次使用read.table时,都会覆盖mydata

If you don't mind using a loop, you can try: 如果您不介意使用循环,可以尝试:

file.names    <- paste("rundata", 1:100, sep= "") 
tm.names      <- paste("tm",      1:100, sep= "") 
score.names   <- paste("score",   1:100, sep= "") 
current.names <- paste("current", 1:100, sep= "") 

my.data.list <- list()
for(i in 1:100){
  my.data.list[[i]] <- read.table(file.names[i], sep= " ", 
                                  col.names=c(tm.names[i], score.names[i], 
                                              current.names[i])            )
}
my.data <- do.call(cbind, my.data.list)
rm(my.data.list, file.names, tm.names, score.names, current.names)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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