The variable name in your call to assign should vary within the for
loop, otherwise you're always assigning the value to the same variable.
Consider the following example,
listOfNames <- c("a", "b", "c")
listOfVariables <- c("vara", "varb", "varc")
for(index in seq_along(listOfNames)){
print(index) # integer sweeping the two lists
print(paste("assigning variable", listOfNames[index], "to ",
listOfVariables[index]))
assign(listOfNames[index], listOfVariables[index])
}
# or more succinctly
mapply(assign, x=listOfNames, value=listOfVariables)
HTH,
baptiste
On 27 Mar 2009, at 18:11, Steve Murray wrote:
Dear all,
I think I'm nearly there in writing R code which will read in files
with two variable parts to the file name and then assigning these
file names to objects, which also have two variable parts. I have
got the code running without encountering errors, however, I receive
50+ of the same warnings:
1: In assign(paste("Fekete_", index$year, index$month, sep =
""), ... :
only the first element is used as variable name
And it's true, when I do ls() only Fekete198601 has been assigned.
I've attempted to rectify this, but have only come up against
further errors.
The code as it stands, is as follows:
# READ IN FILES FROM DISK
# File names have two variable parts: creating a 'file index' is a
two-step process
index <- expand.grid(year = sprintf("%04d", seq(1986, 1995)), month
= sprintf("%02d", 1:12))
filelist <- paste("C:\\Documents and Settings\\Data\
\comp_runoff_hd_", paste(index$year, index$month, sep=''), '.asc',
sep='')
filelist
# Assign file names to individual objects with variable name
components
for (i in filelist) {
assign(paste("Fekete_",index$year, index$month,
sep=''),read.table(file=i, header=FALSE, sep=" "))
update <- substr(i,35,55) # substring - 2nd argument is
character at which extraction is to begin, 3rd argument is where
extraction ends.
print(c("LOADED FILE:",update), quote=FALSE)
}
ls()
[1] "Fekete_198601" "filelist" "i" "index"
[5] "update"
Why is it that only Fekete_198601 has had data assigned to it (there
should be 120 such objects in total) and how do I go about solving
this?
Many thanks again for any help offered,
Steve
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
_____________________________
Baptiste AuguiƩ
School of Physics
University of Exeter
Stocker Road,
Exeter, Devon,
EX4 4QL, UK
Phone: +44 1392 264187
http://newton.ex.ac.uk/research/emag
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.