问题
I'm new in R. I've been reading a lot of forums but I can't find a solution, and I think it couldn't be as difficult.
I want that R reads a data file and create a dataframe with all the data. Then, I want to create a new dataframe with a subset of the original once. For one data file it's easy, and the code I use is as follows (datainfo is a vector with the information of variables):
var1 <- read.fwf("file_var1", widths = datainfo$lenght, col.names= datainfo$names)
var1_5 <- subset(var1, ZONE==5)
It works fine. But now I want to do the same process with a lot of data files (file_var1, file_var2, file_var3....). For the purpose I try to use a FOR, with the help of paste and assign functions:
for (i in c(1:10)) {
assign(paste("var", i, sep=""), read.fwf(paste("file_var", i, sep=""), widths = datainfo$lenght, col.names= datainfo$names))
assign(paste("var", i, "_5", sep=""), subset(paste("var", i, sep=""), ZONE==5)
}
The first line into the FOR works fine. But the second line fails. The error is:
Error in subset.default(paste("var", i, sep = ""), ZONE == 5) :
object 'ZONE' not found
I've noted that a possible problem could be that paste function returns a character vector, and then subset function don't read it as a dataframe. Can I use paste function in the subset function to refer a R object? or there is another function better to do this?
Thank you very much to all!
来源:https://stackoverflow.com/questions/49655013/r-use-paste-function-as-a-object-in-subset-function