我有這段代碼根據該列中重復值的次數計算向量“week1”(在練習中預定義)。我需要使用函式 apply 創建一個對其他 6 列(從 2 到 7)執行相同操作的函式,但我對函式有點掙扎。
這是一段代碼:
matrix <- matrix(1, 16, 7)
week1 <- matrix[,1]
times <- tabulate(week1, 4)
vectorW1 <- c(1/times[1], 1-1/times[1], 1/times[2], 1-1/times[2],
1/times[3], 1-1/times[3],1/times[4], 1-1/times[4])
提前感謝大家的幫助!
uj5u.com熱心網友回復:
我不知道這段代碼試圖做什么,也不知道目標函式試圖做什么。
首先,讓我們把它變成一個函式
mat_to_weights <- function(data) {
stopifnot(inherits(data, "matrix"))
result <- matrix(NA, nrow = 8, ncol = ncol(data))
for (col in seq_len(ncol(data))) {
week <- data[, col]
week
times <- tabulate(week, 4)
times
vector <-
c(
1 / times[1],
1 - 1 / times[1],
1 / times[2],
1 - 1 / times[2],
1 / times[3],
1 - 1 / times[3],
1 / times[4],
1 - 1 / times[4]
)
result[,col] <- vector
}
result
}
mat_to_weights(data = matrix)
> mat_to_weights(data = matrix)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 0.0625 0.0625 0.0625 0.0625 0.0625 0.0625 0.0625
[2,] 0.9375 0.9375 0.9375 0.9375 0.9375 0.9375 0.9375
[3,] Inf Inf Inf Inf Inf Inf Inf
[4,] -Inf -Inf -Inf -Inf -Inf -Inf -Inf
[5,] Inf Inf Inf Inf Inf Inf Inf
[6,] -Inf -Inf -Inf -Inf -Inf -Inf -Inf
[7,] Inf Inf Inf Inf Inf Inf Inf
[8,] -Inf -Inf -Inf -Inf -Inf -Inf -Inf
接下來,讓我們嘗試使用來自 的虛擬矩陣,而不是 1 的矩陣pracma::magic(n)。
> mat_to_weights(data = pracma::magic(1))
[,1]
[1,] 1
[2,] 0
[3,] Inf
[4,] -Inf
[5,] Inf
[6,] -Inf
[7,] Inf
[8,] -Inf
> mat_to_weights(data = pracma::magic(2))
[,1] [,2]
[1,] 1 Inf
[2,] 0 -Inf
[3,] Inf 1
[4,] -Inf 0
[5,] Inf 1
[6,] -Inf 0
[7,] 1 Inf
[8,] 0 -Inf
Warning message:
In pracma::magic(2) : There is no magic square of order 2.
> mat_to_weights(data = pracma::magic(3))
[,1] [,2] [,3]
[1,] Inf 1 Inf
[2,] -Inf 0 -Inf
[3,] Inf Inf 1
[4,] -Inf -Inf 0
[5,] 1 Inf Inf
[6,] 0 -Inf -Inf
[7,] 1 Inf Inf
[8,] 0 -Inf -Inf
> mat_to_weights(data = pracma::magic(4))
[,1] [,2] [,3] [,4]
[1,] Inf Inf Inf 1
[2,] -Inf -Inf -Inf 0
[3,] Inf 1 Inf Inf
[4,] -Inf 0 -Inf -Inf
[5,] Inf Inf 1 Inf
[6,] -Inf -Inf 0 -Inf
[7,] 1 Inf Inf Inf
[8,] 0 -Inf -Inf -Inf
> mat_to_weights(data = pracma::magic(5))
[,1] [,2] [,3] [,4] [,5]
[1,] Inf Inf 1 Inf Inf
[2,] -Inf -Inf 0 -Inf -Inf
[3,] Inf Inf Inf 1 Inf
[4,] -Inf -Inf -Inf 0 -Inf
[5,] Inf Inf Inf Inf 1
[6,] -Inf -Inf -Inf -Inf 0
[7,] 1 Inf Inf Inf Inf
[8,] 0 -Inf -Inf -Inf -Inf
同樣,不清楚這是應該做的,但該功能有效。
讓我們記住應用來重寫它。
mat_to_weights <- function(data) {
stopifnot(inherits(data, "matrix"))
result <- matrix(NA, nrow = 8, ncol = ncol(data))
apply(data, 2, function(week) {
times <- tabulate(week, 4)
vector <-
c(
1 / times[1],
1 - 1 / times[1],
1 / times[2],
1 - 1 / times[2],
1 / times[3],
1 - 1 / times[3],
1 / times[4],
1 - 1 / times[4]
)
vector
})
}
其他要考慮的實作當然是sweep,但現在這可行..
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/523702.html
標籤:r功能制表
