Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-17 of 17 total

sort a data.frame by a given column

data <- sort.data.frame(data, key = "LOC")


where the function "sort.data.frame" is as follows:

sort.data.frame <- function(x, key, ...) {
    if (missing(key)) {
        rn <- rownames(x)
        if (all(rn %in% 1:nrow(x))) rn <- as.numeric(rn)
        x[order(rn, ...), , drop=FALSE]
    } else {
        x[do.call("order", c(x[key], ...)), , drop=FALSE]
    }
}

barplot the lines of code by module

The CSV file "loc.csv" contains the following:

Module LOC
a.rb 100
b.rb 120
c.rb 54


The following R code creates the barplot image "loc.png":

data <- read.csv(file="loc.csv", sep = " ", header = TRUE, row.names = "Module")
png("loc.png", width = 640, height = 480)
barplot(data$LOC, names = rownames(data), ylim = c(0, 250), main = "Lines of code by module", ylab = "Lines of code", xlab = "Module")
dev.off()

Calculate Eigenvalues of a given matrix m.

> sm <- eigen(m, sym=TRUE)
> V <- sm$vectors
> t(V) %*% V
> V %*% diag(sm$values) %*% t(V)

Delete particular rows from matrix.

> x <- matrix(1:10,,2)
> x[x[,1]%in%c(2,3),]
> x[!x[,1]%in%c(2,3),]


from Peter Malewski or from Peter Dalgaard:

> mat[!(mat$first %in% 713:715),]

Create a multidimensional matrix.

Brian Ripley said:

> my.array<-array(0,dim=c(10,5,6,8))


will give you a 4-dimensional 10 x 5 x 6 x 8 array.

Or

> array.test <- array(1:64,c(4,4,4))
> array.test[1,1,1]
> 1
> array.test[4,4,4]
> 64

Create an identity matrix.

> diag(n)


Or the long way:

> n<-c(5)
> I <- matrix(0,nrow=n,ncol=n)
> I[row(I)==col(I)] <- 1

Create a vector, append values.

To create a mathematical vector, you can just initialize a column of numbers with c(). As long as all of your input is of the same type, you don't hit any snags. Note the is.vector() function will say this is a vector:

> v <- c(1, 2, 3) 
> is.vector(v) 
« Newer Snippets
Older Snippets »
Showing 11-17 of 17 total