我已從 excel 檔案中讀取資料,并將其制成向量。然后我把它做成一個3d陣列。
形成陣列的向量以及陣列內部現在包含字符,如下所示:
D <- c('g', 't', NA, 'd')
nPeriods = 3
column.names = c('aaa', 'bbb')
row.names = c('jjj', 'hhh')
threeD.names = c(1:nPeriods)
E = array(c(D), dim=c(2, 2, nPeriods),
dimnames = list(row.names, column.names, threeD.names))
但是,現在我想將“g”、“t”等分配為具有起始值的變數,例如
g = 5
t = 2
d = 7
但我知道如何做到這一點的唯一方法是手動找出它是陣列的哪個元素并像這樣分配它,例如
E[1,1,]=5
當它是一個很大的矩陣時,每次我參考一個元素時都很難找到相應的位置。我知道向量的每個元素(不是 NA)都是唯一的,所以我想知道,是否有參考陣列每個元素的快捷方式?(也許在 apply 家族中有一些東西?但有這么多)。
我還需要稍后參考它們來回圈 nPeriods。昨天有人向我展示了我可以這樣做:
for (i in 2:nPeriods){
C[1,1,i]=C[1,1,i-1]*2
}
但在現實生活中,我的矩陣可能非常大,所以我寧愿只能用 d、t 等來參考。
uj5u.com熱心網友回復:
如果將替換值存盤在命名向量中,則可以使用apply按名稱替換元素。apply自動處理回圈,如果所有非 NA 元素都是數字,甚至將結果轉換為數字陣列。請注意,1:3呼叫中的apply是指陣列的三個維度,而不是第三個維度的長度,因此無論陣列有多大,這都應該有效。
values <- c(g = 5,
t = 2,
d = 7)
num_array <- apply(E, 1:3, function(x) values[x])
num_array
, , 1
aaa bbb
jjj 5 NA
hhh 2 7
, , 2
aaa bbb
jjj 5 NA
hhh 2 7
, , 3
aaa bbb
jjj 5 NA
hhh 2 7
您的第二個問題尚不清楚,但您可以which有效地獲取元素。您只需要遍歷切片:
result <- num_array
for (i in 2:dim(num_array)[3]) {
idx <- which(E[, , 1] == 'g', arr.ind = T)
row <- idx[1, 'row']
col <- idx[1, 'col']
result[row, col, i] <- result[row, col, i-1] * 2
}
, , 1
aaa bbb
jjj 5 NA
hhh 2 7
, , 2
aaa bbb
jjj 10 NA
hhh 2 7
, , 3
aaa bbb
jjj 20 NA
hhh 2 7
如果您想存盤每個字符的操作(相對簡單的操作),您可以利用 R 的一些元編程功能:
funcs <- c(g = '*', t = ' ', d = '-')
modifiers <- c(g = 2, t = 3, d = 4)
num_array <- apply(E, 1:3, function(x) values[x])
result <- num_array
for (i in 2:dim(num_array)[3]) {
for (j in names(values)) {
idx <- which(E[, , 1] == j, arr.ind = T)
row <- idx[1, 'row']
col <- idx[1, 'col']
result[row, col, i] <- do.call(funcs[j], args = list(result[row, col, i-1], modifiers[j]))
}
}
, , 1
aaa bbb
jjj 5 NA
hhh 2 7
, , 2
aaa bbb
jjj 10 NA
hhh 5 3
, , 3
aaa bbb
jjj 20 NA
hhh 8 -1
uj5u.com熱心網友回復:
此任務在串列中更易于管理。您可以使用以下內容:
# Example data
D <- c('g', 't', NA, 'd')
nPeriods = 3
column.names = c('aaa', 'bbb')
row.names = c('jjj', 'hhh')
threeD.names = c(1:nPeriods)
E = array(c(D), dim=c(2, 2, nPeriods),
dimnames = list(row.names, column.names, threeD.names))
# Convert array to list
array_list <- lapply(seq(dim(E)[3]), function(x) E[,,x])
# Re-assign values
array_converted <- lapply(array_list, function(x){
x <- ifelse(x == "g", 5, x) # your conversion values
x <- ifelse(x == "t", 2, x)
x <- ifelse(x == "d", 7, x)
x <- apply(x, 2, as.numeric) # Ensures values are numeric
return(x)
})
# For final format as array (if you want)
final_array <- simplify2array(array_converted)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438417.html
