library(animation)
library(lattice)
data(iris)
set.seed(4)
iris.data <- iris[1:100, c(1, 2, 5)]
sample.iS <- c(sample(1:50, 25))
sample.iV <- c(sample(51:100, 25))
iris.data$id <- c(rep(-1, 50), rep(1, 50))
iris.data$intercept <- 1
iS <- iris$Species == "setosa"
iV <- iris$Species == "versicolor"
data <- iris.data
iris.data <- iris.data[sample(c(sample.iS, sample.iV)), ]
w.0 <- as.matrix(runif(3, min = -1, max = 1))
w.t <- w.0
i = 1
while (i <= ani.options("nmax")) {
    matplot(c(3.5, 8), c(1, 4.5), type = "n", xlab = "Length", 
        ylab = "Width", main = "Petal Dimensions in Iris Blossoms")
    matpoints(data[sample.iS, 1], data[sample.iS, 2], pch = "S", 
        col = c(2))
    matpoints(data[sample.iV, 1], data[sample.iV, 2], pch = "V", 
        col = c(4))
    matlines(x <- seq(3.5, 8, 0.1), (-w.t[1] * x - w.t[3])/w.t[2], 
        col = "grey", lwd = 1)
    legend(6.5, 1.5, c("    Setosa Petals", "Versicolor Petals"), 
        pch = "SV", col = c(2, 4))
    j <- (i - 1)%%50 + 1
    matpoints(iris.data[j, 1], iris.data[j, 2], pch = 1, 
        cex = 2)
    matlines(c(0, iris.data[j, 1]), c(0, iris.data[j, 2]), 
        lty = 2, pch = 1, cex = 2, col = "grey")
    abline(b = w.t[2]/w.t[1], a = iris.data[j, 2] - w.t[2]/w.t[1] * 
        iris.data[j, 1], lty = 2, col = "grey")
    xv <- t(as.matrix(iris.data[j, c(1, 2, 5)]))
    yv <- sign(t(w.t) %*% xv)
    if (yv * iris.data[j, c(4)] < 0) 
        w.t <- w.t + xv %*% iris.data[j, c(4)]
    matlines(x <- seq(3.5, 8, 0.1), (-w.t[1] * x - w.t[3])/w.t[2], 
        col = 2, lwd = 1)
    ani.pause()
    i = i + 1
}
## R version 2.12.0 (2010-10-15)
## Platform: i686-pc-linux-gnu (32-bit)
## Other packages: animation 2.0-3, lattice 0.19-13