Reputation: 1206
guys, thanks for read this. This is my first time writing a program so pardon me if I make stupid questions.
I have bunch of .csv files named like: 001-XXX.csv;002-XXX.csv...150-XXX.csv. Here XXX is a very long name tag. So it's a little annoying that every time I need to type read.csv("001-xxx.csv"). I want to make a function called "newread" that only ask me for the first three digits, the real id number, to read the .csv files. I thought "newread" should be like this:
newread <- function(id){
as.character(id)
a <- paste(id,"-XXX.csv",sep="")
read.csv(a)
}
BUt R shows Error: unexpected '}' in "}" What's going wrong? It looks logical.
I am running Rstudio on Windows 8.
Upvotes: 1
Views: 1848
Reputation: 49660
This is not specifically an answer to your question (others have covered that), but rather some advice that may be helpful for accomplishing your task in a different way.
First, some of the GUI's for R have file name completion. You can type the first part: read.csv("001-
and then hit a key or combination of keys (In the windows GUI you press TAB) and the rest of the filename will be filled in for you (as long as it is unique).
You can use the file.choose
or choose.files
functions to open a dialog box to choose your file using the mouse: read.csv(file.choose())
.
If you want to read in all the above files then you can do this in one step using lapply
and either sprintf
or list.files
(or others):
mycsvlist <- lapply( 1:150, function(x) read.csv( sprintf("%03d-XXX.csv", x) ) )
or
mvcsvlist <- lapply( list.files(pattern="\\.csv$"), read.csv )
You could also use list.files
to get a list of all the files matching a pattern and then pass one of the returned values to read.csv
:
tmp <- list.files(pattern="001.*csv$")
read.csv(tmp[1])
Upvotes: 0
Reputation: 1735
as.character(id)
will not change id
into a character string. Change it to:
id = as.character(id)
Edit: According to comments, you should call newread()
with a character paramter, and there is no difference between newread(001)
and newread(1)
.
Upvotes: 1