Friday, March 11, 2011

How to plot derivative in R

Suppose we have two lists x and y of equal size, and we want to plot x vs y1=dy/dx. How to do this in R?

M<-read.table("tmp.txt")
x<-M[,1]
y<-M[,2]
k<-length(x)
y1<-c()
for(i in c(1:k-1)) {
t<-(y[i+1]-y[i])/(x[i+1]-x[i])
y1<-c(y1, t)
}
y1<-c(y1, t)
plot(x,y1)

2 comments:

אהרן said...

In Matlab:

M = dlmread('tmp.txt');
x = M(:,1);
y = M(:,2);
k = length(x);
y1 = zeros(k,1);
for i=1:k-1,
y1(i) = (y(i+1)-y(i))/(x(i+1)-x(i));
end
y1(k) = y1(k-1);
plot(x,y1);

Anonymous said...

Another version with R :
M.diff<-apply(M,2,diff)
derivate<-M.diff[,2]/M.diff[,1]
plot(x,derivate)

Visitors