For this example, I use ggplot2 and so you need to enter:

if (!require(ggplot2)) install.packages('ggplot2')
## Loading required package: ggplot2

This basically installs the Library ggplot2 if it is not in your system and then loads the required functions.

Let's first assume we have different data with different number of points.

valx1<-c(1,2,3,4,5,6)
valy1<-c(2,3,8,9,10,12)
valx2<-c(2,7,8,9)
valy2<-c(3,10,11,12)

We will first combine all x (y) values in a single vector. Then, we will define a new vector (allexp), which consists in a repetition of identical characters, called factors in R (factors are categorical variables). Finally we will create data.frame (a structure to store vectors of equal lengths) with all three vectors (allx, ally and allexp).

allx<-c(valx1,valx2) # combine x values
ally<-c(valy1,valy2) # combine y values
exp1<-rep('exp1',length(valx1)) # I repeat 'exp1' times length(valx1)
exp2<-rep('exp2',length(valx2)) # I repeat 'exp2' times length(valx2)
allexp<-as.factor(c(exp1,exp2)) # in R 4+, exp1 and exp2 are characters NOT factors :-(
df<-data.frame(allx,ally,allexp)
df
##    allx ally allexp
## 1     1    2   exp1
## 2     2    3   exp1
## 3     3    8   exp1
## 4     4    9   exp1
## 5     5   10   exp1
## 6     6   12   exp1
## 7     2    3   exp2
## 8     7   10   exp2
## 9     8   11   exp2
## 10    9   12   exp2

Notice how one can get certain columns and lines:

#Return the first column
df[,1]
##  [1] 1 2 3 4 5 6 2 7 8 9
#Return the first column using explicit names
df$allx
##  [1] 1 2 3 4 5 6 2 7 8 9
#Return the second line
df[2,]
##   allx ally allexp
## 2    2    3   exp1
#Return first 2 columns of line 3
df[3,1:2]
##   allx ally
## 3    3    8

As you can see (df), we have assigned a specific factor to each experiment. Note that in recent version of R, we need to explicitly mention that characters are factors. Having defined a data.frame (df), we can fit both experiments at once. For this, we have to specify that both a and b parameters are factor-dependent (a[df$allexp] and b[df$allexp]).

fitexp<-nls(df$ally ~ df$allx*a[df$allexp]+b[df$allexp],start=list(a=c(1,1),b=c(1,1)))

Amost done ... The script below allows to plot both experiments on a single graph.

p1<-ggplot(df)+geom_point(aes(x=allx, y=ally, colour=factor(allexp)),size=4,shape=18)+
               geom_line(aes(x=allx, y=predict(fitexp), colour=factor(allexp)),lwd=1.5)+
               scale_color_manual(values=c("#000000", "#C8C8C8") )+ # this can removed 
               theme_light()
p1

summary(fitexp)$coefficients[,1:2] # estimates
##     Estimate Std. Error
## a1 2.0571429  0.2285167
## a2 1.3103448  0.1775162
## b1 0.1333333  0.8899447
## b2 0.4827586  1.2489371
Comments

Description