由于您没有提供示例数据,我将使用 R 中的 iris 数据:
mydata<-iris
mydata$Petal.Width<-as.factor(mydata$Petal.Width)
str(mydata)
str(mydata)
'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : Factor w/ 22 levels "0.1","0.2","0.3",..: 2 2 2 2 2 4 3 2 2 1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
myreg<-lm(Sepal.Length~Sepal.Width+Petal.Width+Species,data=mydata)
k<-length(levels(mydata$Petal.Width))
mycoef<-coef(myreg)[3:(k+1)]
mycoef<-data.frame(mycoef)
> head((mycoef)
mycoef
Petal.Width0.2 0.13981323
Petal.Width0.3 0.17193663
Petal.Width0.4 0.20220902
Petal.Width0.5 0.31915175
Petal.Width0.6 0.08864592
mycoef$var<-rownames(mycoef)
rownames(mycoef)<-1:dim(mycoef)[1]
mycoef[,c("var","mycoef")]
mycoef[,c("var","mycoef")]
var mycoef
1 Petal.Width0.2 0.13981323
2 Petal.Width0.3 0.17193663
3 Petal.Width0.4 0.20220902
4 Petal.Width0.5 0.31915175
更新:
mycoef$var1<-substring(mycoef$var,12,15)
myout<-merge(mydata1,mycoeff,by.x="Petal.Width",by.y="var1")
> head(myout)
Petal.Width Sepal.Length Sepal.Width Petal.Length Species var mycoef
1 0.2 4.9 3.0 1.4 setosa Petal.Width0.2 0.1398132
2 0.2 4.7 3.2 1.3 setosa Petal.Width0.2 0.1398132
3 0.2 4.6 3.1 1.5 setosa Petal.Width0.2 0.1398132
4 0.2 5.0 3.6 1.4 setosa Petal.Width0.2 0.1398132
5 0.2 5.1 3.5 1.4 setosa Petal.Width0.2 0.1398132
6 0.2 5.4 3.7 1.5 setosa Petal.Width0.2 0.1398132