开发者

Convert txt file to csv and extract selected rows

I have 500 files (saved in the same directory).

All these files have the same format, as follows. Although excel can recognize them having 3 columns, R only reads one column if I use x <- read.csv(xxx.txt, header=T). I guess there is a smarter way of doing this.

4077    40770     3.083 
4078    40780     2.985 
4079    40790     2.946 
4080    40800     3.010 
4081    40810     2.956 
4082    4开发者_高级运维0820     3.080 
4083    40830     3.130 
4084    40840     3.167 
4085    40850     3.054 

After loading all these files to R, I want to extract only 0, 100th, 200th, 300th,....9000th rows and save them in another directory with the same file name in 500 separated files.

Is it possible to be done automatically with R?


I think that you would improve your code using the read.table() function to import free formated (delimited) data files instead of the rad.csv(), which was written specifically for comma delimited files. And as DWin pointed you, there is no row 0 in R. You could try this way:

directory <- "your.work.directoty" # where your data files are. 
                                   # It depends on your OS (Windows, Linux, MacOS)
ndirectory <- "your.new.directory"
files <- dir(directory)
files.to.read <- paste(directory, files, sep="/") 
files.to.write <- paste(ndirectory, files, sep="/")

for(i in 1:length(files.to.read) )
{
    d <- read.table(files.to.read[i], header=TRUE)
    temp <- d[c(1,seq(100, 9000, by=100)), ]
    write.table(temp, file=files.to.write[i], 
                row.names=FALSE)
}

Hope this help.


Loading:

  1. Create a list with their names most easily done with> list.files( )

  2. Loop through that list using read.table with either no sep argument or sep="\t" (no commas or header in that file as it appears now .)

  3. Perhaps: lapply(flist, function(x) assign(x, read.table(x) ) ...and rbind these together, perhaps with something like bigfile <- do.call(rbind, flist)

    There are lots of examples in the rhelp archive and on SO of doing this;

Loop in R loading files

With R, loop over data frames, and assign appropriate names to objects created in the loop

How to read.table() multiple files into a single table in R?

Extracting (There is no zero row in R):

subextract <- bigfile[ seq(1, 9001 , by=100), ]
write.csv(subextract, file="smaller.csv")   # will have commas
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜