[英]R: apply on all matrix elements
這似乎太基礎了,我幾乎不敢問這個問題,但是我無法解決這個問題。 與此等效的是什么。 這是一個人為的示例,因為我想使用行和列索引訪問每個單元格的數據,但它很好地表示了問題。
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")
}
這是實際的問題。 我正在嘗試在網格上繪制矩陣。 我知道textplot可以繪制矩陣,但是我需要對網格進行更多控制。 文本的位置取決於行和列的索引。 代碼如下:
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))
從?apply
:
MARGIN:一個給出下標的向量,該功能將被應用到下標。 例如,對於矩陣,“ 1”指示行,“ 2”指示列,“ c(1,2)”指示行和列。 在“ X”已命名為dimnames的情況下,它可以是選擇尺寸名稱的字符向量。
所以你要:
ndat<-matrix(c(1:100), ncol=10)
apply(ndat, 1:2, cat)
不知道自己想做什么很難說,但是矩陣是具有維的向量。 因此矢量化函數通常通常可以直接正常工作:
ndat<-matrix(c(1:100), ncol=10)
ndat^2
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 121 441 961 1681 2601 3721 5041 6561 8281
[2,] 4 144 484 1024 1764 2704 3844 5184 6724 8464
[3,] 9 169 529 1089 1849 2809 3969 5329 6889 8649
[4,] 16 196 576 1156 1936 2916 4096 5476 7056 8836
[5,] 25 225 625 1225 2025 3025 4225 5625 7225 9025
[6,] 36 256 676 1296 2116 3136 4356 5776 7396 9216
[7,] 49 289 729 1369 2209 3249 4489 5929 7569 9409
[8,] 64 324 784 1444 2304 3364 4624 6084 7744 9604
[9,] 81 361 841 1521 2401 3481 4761 6241 7921 9801
[10,] 100 400 900 1600 2500 3600 4900 6400 8100 10000
我之所以這樣說,是因為與apply
方式相比,這樣做可能會大大提高速度。
您正在做的事情可以這樣模擬:
apply(ndat, 1, function (k) cat(k, "\n"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.