R: How to read different files into a two-dim vector?
I have an R
newbie question about storing data.
I have 3 different files, 开发者_StackOverflow中文版each of which contains one column. Now I would like to read them into a structure x
so that x[1]
is the column of the first file, x[2]
is the column of the second file, etc. So x
would be a two-dim vector.
I tried this, but it wants x[f]
to be a single number rather than a whole vector:
files <- c("dir1/data.txt", "dir2b/data.txt", "dir3/data2.txt")
for(f in 1:length(files)) {
x[f] <- scan(files[f])
}
How can I fix this?
Lists should help. Try
x <- vector(mode="list",length=3)
before the loop and then assign as
x[[f]] <- read.table(files[f])
I would recommend against scan
; you should have better luck with read.table()
and its cousins like read.csv
.
Once you have x
filled, you can combine as e.g. via
y <- do.call(cbind, x)
which applies cbind
-- a by-column combiner -- to all elements of the list x
.
精彩评论