[R] assigning NA's

Thomas Lumley tlumley at u.washington.edu
Tue Jan 22 19:01:09 CET 2002


On Tue, 22 Jan 2002, Patrick Buetzberger wrote:

> I've had a question a few moments ago about how to create multiple
> objects from multiple files within a loop. Thanks for the quick answers,
>
> it worked with "assign", like this:
>
> for(i in seq(1,nfn,1)){
>  fin<-paste("/home/klimet/patrick/LAEGEREN/NEBEL/FOGEVENT2000/",fn[i],sep="")
>
>  assign(paste("f", i, sep = ""), as.matrix(read.table(fin,skip=1)))
> }
>
> I've tried to use the same command for assigning NA's to missing values
> (=-999)  in each object created with above loop, like this:
> for(i in seq(1,nfn,1)){
>  assign(paste("f", i, sep = "")[paste("f", i, sep = "") < -500.], NA)
> }
>
> This did not work, it created an error "invalid first argument"

assign() doesn't dispatch things like f1[10]<-NA to the "[<-" methods, so
this kind of approach won't work.

> I've also tried:
> for(i in seq(1,nfn,1)){
>  paste("f", i, sep = "")[paste("f", i, sep = "") < -500.] <- NA
> }
>
> This also created an error. Any clues about how to handle this problem?

This kind of approach can work, but you need to create expressions rather
than strings.

  expr<-substitute(fi[fi< -500]<-NA,
		list(fi=as.name(paste("f",i,sep=""))))

creates expressions like
	f1[f1 < -500] <- NA
and these need to be evaluated in the current environment
	eval(expr,envir=environment())
or possibly in the global environment
	eval(expr,envir=.GlobalEnv)

Note that it would be much easier to create a single object (a list)
rather than multiple objects, and it might well be easier to manipulate
them that way afterwards.

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list