0

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 something and then to the next one on the list. But I get an error there. What am I doing wrong?

4

2 回答 2

2

您可以使用 paste 创建公式的字符串版本,包括您想要的变量名称,然后使用as.formulaformula函数将其转换为公式以传递给 nls。

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

另一种选择是使用 bquote 函数将变量名插入到函数调用中,然后对函数调用求值。

于 2010-09-16T15:51:20.017 回答
0

前段时间我和 R 一起工作过,也许你可以试试这个:

你想要的是创建一个包含变量列表的公式,对吗?

因此,如果响应变量是列表的第一个元素,而其他变量是解释变量,则可以这样创建公式:

my_feature[0] ~ reduce("+",my_feature[1:]) 。这可能会奏效。

通过这种方式,您可以创建取决于 my_features 中的变量的公式。

于 2010-09-16T12:21:03.337 回答