This seems so elementary that I am almost embarrassed to ask the question but I just can't get this to work. What would be the equivalent apply for this. This is a contrived example as I want to access the data for each cell with its row and column index but it represents the issue well.
ndat<-matrix(c(1:100), ncol=10)
for (i in 1:nrow(ndat)) {
for (j in 1:ncol(ndat)) {
cat(ndat[i,j]," ")
}
cat("\n")
}
Here is the actual problem. I am trying to plot the matrix on a grid. I know that textplot can plot matrices but I need more control on the grid. The location of the text depends on the row and column indices. The code is as follows:
plot.new()
tlx <- 0.04
tly <- 0.96
label_shift <- 0.04
text(tlx + label_shift, tly, "Columns", cex=1, adj=c(0,0))
text(tlx, tly - label_shift, "Rows", cex=1, adj=c(0,1), srt=-90)
ndat<-matrix(c(1:100), ncol=10)
dimnames(ndat) <- list(paste("R",1:10,sep=""), paste("C",1:10,sep=""))
row_name_space <- 0.1
col_name_space <- 0.1
data_width <- 0.075
data_height <- 0.075
x1 <- 1.5 * tlx
x2 <- x1 + row_name_space + ncol(ndat) * data_width
y1 <- tly - 0.5*tlx
y2 <- y1 - col_name_space - nrow(ndat) * data_height
lines(c(x1,x1), c(y1,y2))
lines(c(x1,x2), c(y1,y1))
vertical_lseg <- function(n) {
lx <- x1 + row_name_space + (n - 1) * data_width
xv <- c(lx, lx)
yv <- c(y1, y2)
lines (xv, yv)
}
sapply(1:(ncol(ndat)+1), vertical_lseg)
horizontal_lseg <- function(n) {
ly <- y1 - col_name_space - (n - 1) * data_height
xv <- c(x1, x2)
yv <- c(ly, ly)
lines (xv, yv)
}
sapply(1:(nrow(ndat)+1), horizontal_lseg)
sapply(1:nrow(ndat), function(x) text(1.5 * tlx + row_name_space / 2, tly - 0.5*tlx - col_name_space - (x - 0.5) * data_height, rownames(ndat)[x], adj=c(0.5,0.5), cex=1))
sapply(1:ncol(ndat), function(x) text(1.5*tlx + col_name_space + (x - 0.5) * data_width, tly - 0.5*tlx - col_name_space /2, colnames(ndat)[x], adj=c(0.5,0.5), cex=1))
# This is where the text would be plotted. The calculation of x and y is right but the number of elements that outer produces seems to be 10,000
# rather than 100
outer(1:nrow(ndat), 1:ncol(ndat), FUN=function(r,c) text(1.5*tlx + col_name_space + (c - 0.5) * data_width,
tly - 0.5*tlx - col_name_space - (r - 0.5) * data_height,
toString(ndat[r,c]), adj=c(0.5,0.5), cex=1))