开发者

R: How to read different files into a two-dim vector?

开发者 https://www.devze.com 2023-01-11 11:41 出处:网络
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] i

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.

0

精彩评论

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