我有一個包含數值和分類變數的資料框。
資料框有 2 個我需要分組的鍵。當行按 so & li 鍵分組時,則需要根據模式和數字按平均值選擇分類變數。
SO LI A B
1 2000 20 P 22
2 2000 20 P 40
3 1000 10 Q 80
輸出需要是,
SO LI A B
1 2000 20 P 31
2 1000 10 Q 80
到目前為止,我使用了以下代碼。
library(plyr)
groupColumns = c("so","li")
dataColumns = c(colnames(numericalColumns(Planning_DF)))
res = ddply(Planning_DF, groupColumns, function(x) colMeans(x[dataColumns]))
head(res)
所以數字列分組和平均發生。如何獲得分類變數模式?
uj5u.com熱心網友回復:
使用它更容易 dplyr
library(dplyr)
groupColumns = c("SO","LI")
Planning_DF %>%
group_by(across(all_of(groupColumns))) %>%
summarise(across(where(is.numeric), mean),
across(where(is.character), Mode), .groups = 'drop')
-輸出
# A tibble: 2 × 4
SO LI B A
<int> <int> <dbl> <chr>
1 1000 10 80 Q
2 2000 20 31 P
在哪里
Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
如果我們需要在 中執行此操作plyr,請colwise與基于列型別執行mean或的自定義函式一起使用Mode
f1 <- function(x) if(is.numeric(x)) mean(x, na.rm = TRUE) else Mode(x)
plyr::ddply(Planning_DF, .variables = groupColumns,
.fun = plyr::colwise(f1))
-輸出
SO LI A B
1 1000 10 Q 80
2 2000 20 P 31
資料
Planning_DF <- structure(list(SO = c(2000L, 2000L, 1000L), LI = c(20L, 20L,
10L), A = c("P", "P", "Q"), B = c(22L, 40L, 80L)),
class = "data.frame", row.names = c("1",
"2", "3"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327590.html
標籤:r
