views:

79

answers:

2

I have this feature_list that contains several possible values, say "A", "B", "C" etc. And there is time in time_list.

So I will have a loop where I will want to go through each of these different values and put it in a formula.

something like for(i in ...) and then my_feature <- feature_list[i] and my_time <- time_list[i]

then i put the time and the chosen feature to a dataframe to be used for regression

feature_list<- c("GPRS")
time_list<-c("time")
calc<-0

feature_dim <- length(feature_list)
time_dim <- length(time_list)

data <- read.csv("data.csv", header = TRUE, sep = ";")
result <- matrix(nrow=0, ncol=5)
errors<-matrix(nrow=0, ncol=3)

for(i in 1:feature_dim) {
    my_feature <- feature_list[i]
    my_time <- time_list[i]

    fitdata <- data.frame(data[my_feature], data[my_time])

    for(j in 1:60) {

        my_b <- 0.0001 * (2^j)

        for(k in 1:60) {
            my_c <- 0.0001 * (2^k)
            cat("Feature: ", my_feature, "\t")
            cat("b: ", my_b, "\t")
            cat("c: ", my_c, "\n")

            err <- try(nlsfit <- nls(GPRS ~ 53E5*exp(-1*b*exp(-1*c*time)), data=fitdata, start=list(b=my_b, c=my_c)), silent=TRUE)
            calc<-calc+1

            if(class(err) == "try-error") {
                next
            }

            else {
                coefs<-coef(nlsfit)
                ess<-deviance(nlsfit)
                result<-rbind(result, c(coefs[1], coefs[2], ess, my_b, my_c))
            }
    }
} 
}

Now in the nls() call I want to be able to call my_feature instead of just "A" or "B" or somethingh and then to the next one on the list. But I get an error there. What am I doing wrong?

**Note: Though I have put it in the title, this is R that I am implementing it in.

A: 

I worked with R a while ago, maybe you can give this a try:

What you want is create a formula with a list of variables right?

so if the response variable is the first element of your list and the others are the explanatory variables you could create your formula this way:

my_feature[0] ~ reduce("+",my_feature[1:]) . This might work.

this way you can create formulae that depends on the variables in my_features.

Arthur Rizzo
the function is spelled with a capital (Reduce), very important in R. Next to that, Reduce() **applies** the function "+", so you can't use it to build a formula. You either get the sume of my_feature[1:] or the notice that you try to apply a non-numeric argument to a binary operator.
Joris Meys
+2  A: 

You can use paste to create a string version of your formula including the variable name you want, then use either as.formula or formula functions to convert this to a formula to pass to nls.

as.formula(paste(my_feature, "~ 53E5*exp(-1*b*exp(-1*c*time))"))

Another option is to use the bquote function to insert the variable names into a function call, then eval the function call.

Greg Snow