dimoftest <- dim(test) # 获取数据维数
factoftest <- c() #定义factor数组
k <- 2 #定义你的那个变量的列k,你自己设定
#循环找出k列大于k-1列10%的序号,并将factor数组设为1,否则为0
for(i in 1:dimoftest){
if((test[i,k]- test[i,k-1])/test[i,k-1] >0.1) factoftest[i] = 1
else factoftest[i] = 2
}
factoftest #显示数组
#创建一个factor因子,标记为1,2,文本也设为1,2
newfactor <- factor(factoftest,levels = c(1,2), labels = c("1","2"))
#合并到数据中
test <- data.frame(test, newfactor)
#查看
test
不明白的话继续问
nls的数据源必须有误差。不能精确等于公式返回值(零残差)。循环次数大于50通常是使用 函数精确返回值 作为数据源去拟合函数。必须给y值加上随机误差。
z=function(x,a,b){a*sin(x)+b*cos(x)}x=seq(1,10,9/500)
y=z(x,1,1) # a=1 b=1 是期望拟合出的结果。
cor=data.frame(x=x,y=y)
cor$res=runif(length(cor$x),min=-0.005,max=0.005)
cor$yres=cor$y+cor$res
#yres =y加上随机误差,y是精确返回值
> nls(cor$yres~z(cor$x,a,b),data=cor,start=list(a=0.8,b=1.3))
Nonlinear regression model
model: cor$yres ~ z(cor$x, a, b)
data: cor
a b
0.9999 1.0002
residual sum-of-squares: 0.004213
Number of iterations to convergence: 1
Achieved convergence tolerance: 2.554e-07
#使用精确返回值拟合就会出错。
> nls(cor$y~z(cor$x,a,b),data=cor,start=list(a=1,b=1))
Error in nls(cor$y ~ z(cor$x, a, b), data = cor, start = list(a = 1, b = 1)) :
循环次数超过了50这个最大值