我有一個示例資料集:
df <- data.frame(category = c("A", "A", "B", "C", "C", "D", "E", "C", "E", "A", "B", "C", "B", "B", "B", "D", "D", "D", "D", "B"), year = c(1, 2, 1, 2, 3, 2, 3, 1, 3, 2, 1, 1, 2, 1, 2, 3, 1, 2, 3, 1))
并希望創建一個 和 的交叉表,year以便表category中只有 3 個最常見的類別,并且還按出現的總數排序:
1 2 3
B 4 2 0
D 1 2 2
C 2 1 1
使用類似的東西
df %>%
add_count(category) %>%
filter(n %in% tail(sort(unique(n)),3)) %>%
arrange(desc(n)) %>% {table(.$category, .$year)}
將過濾三個最常出現的類別,但不排序表格
1 2 3
B 4 2 0
C 2 1 1
D 1 2 2
uj5u.com熱心網友回復:
這應該給你你想要的。
# Make a table
df.t <- table(df)
# Order by top occurrences (sum over margin 1)
df.t <- df.t[order(apply(df.t, 1, sum), decreasing=TRUE),]
# Keep top 3 results
df.t <- df.t[1:3,]
輸出:
year
category 1 2 3
B 4 2 0
D 1 2 2
C 2 1 1
uj5u.com熱心網友回復:
這不是使用基礎 R 的優雅解決方案,但它可以作業
result <- as.data.frame.matrix(table(df))
result$sum <- rowSums(result)
result <- result[order(-result$sum),]
result <- result[1:3,]
result$sum <- NULL
1 2 3
B 4 2 0
D 1 2 2
C 2 1 1
uj5u.com熱心網友回復:
您希望在創建表后按行和進行排列。如果您想(更多)留在 內tidyverse,例如:
df |>
janitor::tabyl(category, year) |>
arrange(desc(rowSums(across(where(is.numeric))))) |>
head(3)
在這里janitor::tabyl(),但您也可以直接使用dplyr::tally()andtidyr::pivot_longer()或df |> table() |> as.data.frame.matrix()像@Adamm 一樣使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/488579.html
