我嘗試根據一個類別值對表進行子集化。假設我們只想保留泰坦尼克號資料中的成年人。我要做的是:
data("Titanic")
subset(Titanic, Age == "Adult")
這導致錯誤object 'Age' not found。對資料幀使用相同的邏輯有效:subset(as.data.frame(Titanic), Age == "Adult"). 但是我們如何直接對表進行子集化,即不將它們轉換為資料框?
編輯
這Adult是第三維。在我的情況下,我不知道它是哪個維度,即我希望能夠按變數名稱進行子集,如subset(Titanic, Age == "Adult"). 它可以是任何其他基本函式,即我不會被subset. 但我正在尋找基本的 R 解決方案。
我的預期輸出是
structure(c(118, 154, 387, 670, 4, 13, 89, 3, 57, 14, 75, 192, 140, 80, 76, 20), .Dim = c(4L, 2L, 2L), .Dimnames = list(Class = c("1st", "2nd", "3rd", "Crew"), Sex = c("Male", "Female"), Survived = c("No", "Yes")), class = "table")
uj5u.com熱心網友回復:
通過匹配dimnames獲取維度索引,然后使用slice.index:
# user input
x = "Adult"
#get index
ix1 <- which(sapply(dimnames(Titanic), function(i) sum(i == x)) == 1)
ix2 <- which(dimnames(Titanic)[[ ix1 ]] == x)
#subset and restore dimensions
res <- Titanic[ slice.index(Titanic, ix1) == ix2 ]
dim(res) <- dim(Titanic)[ -ix1 ]
#test
all(Titanic[,,"Adult",] == res)
# [1] TRUE
# not identical as the names are missing
identical(Titanic[,,"Adult",], res)
# [1] FALSE
res
# , , 1
#
# [,1] [,2]
# [1,] 118 4
# [2,] 154 13
# [3,] 387 89
# [4,] 670 3
#
# , , 2
#
# [,1] [,2]
# [1,] 57 140
# [2,] 14 80
# [3,] 75 76
# [4,] 192 20
uj5u.com熱心網友回復:
您不是在處理 2 維資料框,而是在處理 4 維陣列。
因此,您必須在正確的維度中指定您的條件,如下所示:
Titanic[,,"Adult",]
當你顯示你的陣列時,你有以下 4 個維度:
1- Class
2- Sex
3- Age
4- Survived
您可以使用“str()”或“dimnames()”獲取維度名稱
str(Titanic)
dimnames(Titanic)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/364206.html
上一篇:如何使用plotly-r在懸停文本中舍入percantage
下一篇:從文本檔案中提取粗體和斜體文本
