我正在向nls()
中输入动态输入,但无法使start
参数起作用。看来我不知道该如何喂给正确的对象。我需要正确结构的对象vars
来满足start
参数。
在此示例中,我的起始值存储在vars
中。我尝试过重塑它以及使用as.vector
,as.array
和as.matrix
等对象类弄乱了,但没有成功。
#need this package for acm.disjonctif()
library(ade4)
#get some fake data going for an ad measurement scenario
durta <- data.frame (
"impact"=c(150,150,350,50,150,150, 140,160,330,80,130,170)
, "spend"= c(1000,1200,2300,500,1300,1000, 1900,1200,2000,500,1000,1400)
, "adtitle"=c("zip","bang","boom","zip","bang","boom", "zip","bang","boom","zip","bang","boom")
, "network"=c("NBC","TNT","NBC","TNT","NBC","TNT", "NBC","TNT","NBC","TNT","NBC","TNT")
)
#making each element from network and adtitle into its own binary dimension
factors <- acm.disjonctif(durta[,3:4])
#getting rid of pesky byproducts
colnames(factors) <- gsub("network.","",gsub("adtitle.","",colnames(factors)))
#going to feed this to nls
input <- data.frame(cbind("impact"=durta$impact,"spend"=durta$spend,factors))
#also need to send these starting values
vars <- data.frame("var"=as.array(letters)[1:ncol(factors)],"start"=0)
#pasting a dynamic formula based on 'input' using as.formula works fine
#tried a similar solution for the starting values, failed
fit <- nls(
as.formula(paste(paste("impact ~ spend*(", paste(paste(vars[,1],"*"),noquote(colnames(input[3:ncol(input)])), collapse="+")),")"))
, data=input
, algorithm = "port"
, start = vars
#, start = c(a=.1,b=.3,c=0.3,d=-.9,e=.2)
# ^ this version works
)
如果满足start
参数,那么我应该得到这个(轻微)错误:
nlsModel(formula,mf,start,wts,upper)中的错误: 初始参数估计时的奇异梯度矩阵
当我将工作的静态代码替换为var
时,我得到了:
nls(as.formula(paste(paste(“ impact〜花*(” ,, paste(paste(vars [,: 'data'中没有起始值的参数:e
对于这个人为的例子,我已经在静态版本中添加了一些合理的起始值来处理第一个错误,但是仍然会抛出该错误。随它吧。那不是我的问题。
答案 0 :(得分:2)
start
必须是命名列表。因此
start = setNames(as.list(vars$start), vars$var)
似乎可以做您想做的事情(获取vars$start
中值的向量,将其转换为列表,并使用vars$var
的对应元素作为其名称)。
对于它的价值,看起来您可以使用lm(impact/spend ~ ., data=input)
...