简体   繁体   English

在R中读取多个文件的特定列

[英]Reading specific column of multiple files in R

I have used the following code to read multiple .csv files in R: 我已使用以下代码读取R中的多个.csv文件:

    Assembly<-t(read.table("E:\\test\\exp1.csv",sep="|",header=FALSE,col.names=c("a","b","c","d","Assembly","f"))[1:4416,"Assembly",drop=FALSE])
    Top1<-t(read.table("E:\\test\\exp2.csv",sep="|",header=FALSE,col.names=c("a","b","c","d","Top1","f"))[1:4416,"Top1",drop=FALSE])
    Top3<-t(read.table("E:\\test\\exp3.csv",sep="|",header=FALSE,col.names=c("a","b","c","d","Top3","f"))[1:4416,"Top3",drop=FALSE])
    Top11<-t(read.table("E:\\test\\exp4.csv",sep="|",header=FALSE,col.names=c("a","b","c","d","Top11","f"))[1:4416,"Top11",drop=FALSE])
    Assembly1<-t(read.table("E:\\test\\exp5.csv",sep="|",header=FALSE,col.names=c("a","b","c","d","Assembly1","f"))[1:4416,"Assembly1",drop=FALSE])
    Area<-t(read.table("E:\\test\\exp6.csv",sep="|",header=FALSE,col.names=c("a","b","c","d","Area","f"))[1:4416,"Area",drop=FALSE])

    data<-rbind(Assembly,Top1,Top3,Top11,Assembly1,Area)

So the entire data is in the folder "test" in E drive. 因此,整个数据都在E驱动器的“ test”文件夹中。 Is there a simpler way in R to read multiple .csv data with a couple of lines of code or some sort of function call to substitute what has been made above? R中是否有更简单的方法来通过几行代码或某种函数调用来读取多个.csv数据,以替代上面所做的事情?

(Untested code; no working example available) Try: Use the list.files function to generate the correct names and then use colClasses as argument to read.csv to throw away the first 4 columns (and since that vector is recycled you will alss throw away the 6th column): (未经测试的代码;没有可用的工作示例)尝试:使用list.files函数生成正确的名称,然后使用colClasses作为read.csv的参数来read.csv前4列(由于该向量已回收,因此您也将抛出移至第六栏):

lapply(list.files("E:\\test\\", patt="^exp[1-6]"), read.csv, 
                       colClasses=c(rep("NULL", 4), "numeric"), nrows= 4416)

If you want this to be returned as a dataframe, then wrap data.frame around it. 如果您希望将其作为数据data.frame返回,则将data.frame包裹在其周围。

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

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