[R] providing a variable as a parameter in a function

Subramanian Karthikeyan Subramanian_Karthikeyan at hc-sc.gc.ca
Wed Oct 22 19:31:30 CEST 2003


>From a data frame, how do we extract a specific column name, and plug that
into a command (eg. for Anova as shown below)

> df = read.delim("mydata.txt")
> y = colnames(df)
> r = ncol(x)

Lets say that in the data frame column 1 contains treatments, column 2
contains doses, and columns 3, 4, 5 etc. are different responses, and I
want to run separate 2-way anovas for each response, i.e. my first anova
will be done using col 1: Treatment, col 2: Dose and Col 3: a response,
second anova will be done using treatment (col1), dose (col2) and another
response (col 4) and so on.

I could use a loop to automate the task.

> for (i in 3:r) {
+ mod = lm(y[i]~Trt*Dose, data = x, contrasts = list(Trt = contr.sum, Dose
= contr.sum))
+ Anova(mod, type = "III")
+ }

The problem is when I directly plug in y[3] for my response variables name,
it gives me an error

Error in model.frame(formula, rownames, variables, varnames, extras,
extranames,  :
        invalid variable type

This is likely because the lm() function wants the actual column name,
rather than a variable containing the column name.

Can someone advice?

Thanks,
Karth.




More information about the R-help mailing list