[R] using names() as a variable in a formula

Sundar Dorai-Raj
2004-02-18T21:00:48Z

femke wrote:

> Greetings List,
>
> I'm having some trouble with the use of the names function in a
formula.  Below is an example of something that works (i.e first line), and the
second line is the same formula which doesn't.  I want to be able to
reference the column of the dataC table so I can run the variogram iteratively
with a loop.
>
>
>>v<-variogram(A1~1,loc=~x+y, dataC)
>>v<-variogram(names(dataC[3])~1,loc=~x+y, dataC)
>
> Error in model.frame(formula, rownames, variables, varnames, extras,
extranames,  :
>         invalid variable type
>
> Where dataC looks like:
>
>         x       y   A1   A2  A3
> 1  514030 4793587  0.0  7.9 0.1
> 2  517995 4792516  5.8  5.1 0.0
> 3  514232 4792210  0.0  6.5 0.0
>
> I though initially that it might need some escape character if quotes are
added, and tried the following, but it looks ok.
>
>
>>names(dataC[3])
>
> [1] "A1"
>
>>mode(names(dataC[3]))
>
> [1] "character"
>
>>v<-variogram(as.character(names(dataC[3]))~1,loc=~x+y, dataC)
>
> Error in model.frame(formula, rownames, variables, varnames, extras,
extranames,  :
>         invalid variable type
>
>>v<-variogram(as.formula((names(dataC[3]))~1),loc=~x+y, dataC)
>
> Error in model.frame(formula, rownames, variables, varnames, extras,
extranames,  :
>         invalid variable type
>
> I'd greatly appreciate any suggestions for fixing this.
>
> Thanks again,
>
> femke
> 	[[alternative HTML version deleted]]
>

You're not building a valid formula. Try this:

v <- list()
for(i in 3:5) {
   gr <- names(dataC[i])
   f <- formula(paste(gr, "1", sep = " ~ "))
   v[[gr]] <- variogram(f, loc = ~ x + y, dataC)
}

BTW, since variogram is not in the base package it would also be helpful
in the future if you add that you are using the spatial package.

HTH,
Sundar