Reputation: 133
I have data files something like
class1 class2 ....
1 1 ....
2 1
If I try to read data file like this
var <- read.table("file path", sep="\t",header=TRUE)
It works correctly, so I can access to the data using 'var' variable. but, If I try to read data using for loop using variable list like this,
var <- c()
for(file in list.files(path="inputDir")){
i <- i+1
var[i] <- read.table("file path", sep="\t", header=TRUE)
}
I get only first column of the file, and can't get full data of the file.
Do I have to make separate variables like var1, var2, ...?
Can't I use var[i]
??
Upvotes: 0
Views: 900
Reputation: 2391
You should use list
to do such work. data.frame
can only store variable with same rows.
var <- list()
i <- 1
for(file in list.files(path="inputDir")){
var[[as.character(i)]] <- read.table("file path", sep="\t", header=TRUE)
i <- i+1
}
I hope this will help you.
I don't if these code can work correctly, and you can debug according to error reports. And if you really do not know how to do it, you should give some sample files, so everyone can debug for you.
Upvotes: 1
Reputation: 1721
With
var <- c()
you create a (numerical) vector. I guess the imported data gets coerced to that format too, which is why you only see 'one column'.
What you want is a list:
var <- list()
Make sure to index it with double brackets afterwards, like so:
var[[i]] = ...
Upvotes: 1