Read a list of files with R, each file contains a list of float numbers. what's the proper way to do it?
Read a list of files with R, each file contains a list of float numbers. what's the proper way to do it?
I'v never used R before. Just want to try a little bit of R
All files contains 121 float numbers, o开发者_高级运维ne number per line
any words will help. Thanks!
What do you want to do with the data in the list of files? Greg's answer shows you one way to read a single file, which you could stick in a loop over the file names. But do you want the results in n R objects or combined in some manner?
For example, I have two files foo.txt and bar.txt in my working directory. I can list all *.txt
files using list.files()
, then operate on that list to read them in and combine them in different ways.
For example: here we combine them into a matrix:
flist <- list.files(pattern = ".txt$") ## so we get only files .txt not .txt~
(f <- sapply(flist, scan))
## or to a data.frame
(df <- data.frame(sapply(flist, scan)))
## fix up the colnames and rownames
colnames(f) <- colnames(df) <- paste("File", seq_along(flist), sep = "")
head(df)
File1 File2
1 12 12
2 23 23
3 34 34
4 45 45
5 6 6
6 67 67
If you wanted to concatenate the files together into one long vector, then we could achieve that with
> do.call(c, lapply(flist, scan))
Read 10 items
Read 10 items
[1] 12 23 34 45 6 67 78 54 34 324 12 23 34 45 6 67 78 54 34
[20] 324
HTH
The scan function is a very basic (but powerful) function for reading in data, you can just do something like:
mydata1 <- scan('your 1st filename here')
and my data will be a vector with the values from the file.
精彩评论