view.seq.R

A few years ago, I wrote an R script called view.seq.R. It draws a sequence alignment of APE’s DNAbin format by using R’s image function.

Although it is a short code (just 50 lines), it did a nice job. It was a good tool for making figures for presentations as well as useful for examining  the alignment with my own eyes. No software I knew had a good “zoom-out” view like this script. As you can see from the picture below, variants and possible errors are easily found.

sqn.matrix

It was in my toolbox for long time. But, sadly I no longer use this function. Now APE has a function called image.DNAbin to do the exactly same thing and more.

I will just put the code of view.seq here.

view.seq <- function(x, col=NULL, sep=FALSE) {
	seq.name <- names(x)

	if (is.list(x)) {
		if (length(unique(unlist(lapply(x, length)))) != 1)
			stop("DNA sequences in list not of the same length.")
		nms <- names(x)
		n <- length(x)
		s <- length(x[[1]])
		x <- matrix(unlist(x), n, s, byrow = TRUE)
	} else if (is.matrix(x)) {
		n <- nrow(x)
		s <- ncol(x)
	}

	#color sequence
	x[(x & as.raw(8)) != 8] <- as.raw(0)	#any ambiguous characters were replaced with 0
	x[is.na(x)] <- as.raw(0)

	#x[x == 240] <- as.raw()

	x[x == 136] <- as.raw(1) #a
	x[x == 24] <- as.raw(2) #t
	x[x == 72] <- as.raw(3) #g
	x[x == 40] <- as.raw(4) #c

	x <- matrix(as.numeric(x), nrow=n, ncol=s)

	if (sep) {
		#insert separaters
		size <- 3
		mat <- matrix(0, nrow=size*nrow(x), ncol=ncol(x))
		for (i in 1:(size-1)) {
			mat[seq(i, nrow(mat), size),] <- x
		}
		mat[seq(size, nrow(mat), size),] <- 0
		x <- mat[-nrow(mat),]
	}

	if (is.null(col)) {
		#color <- c("lightgrey", "red", "blue", "green", "yellow")
		color <- c("lightgrey", "azure", "skyblue", "blue", "darkblue")
	} else {
		color <- c("lightgrey", col)
	}

	image(t(x), col=color)

}

 

Advertisements

One thought on “view.seq.R

  1. Pingback: image.h.R: how to color your bases | Tomochika Fujisawa's site

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s