我似乎找不到解决我问题的答案。
这是示例数据
Credit Card Type Bank Year Total Balance
MASTER CARD BOFA 2017 $100
MASTER CARD BOFA 2017 $100
MASTER CARD BOFA 2017 $700
VISA Wells 2018 $60
VISA Wells 2018 $50
VISA Wells 2018 $60
等
我正在尝试找出如何通过所有变量的总余额获得模式 所以最终会像这样
所需的输出:
Credit Card Type Bank Year Mode
MASTER CARD BOFA 2017 $100
VISA Wells 2018 $60
答案 0 :(得分:1)
按照弗兰克的建议,使用stackoverflow.com/q/2547402中的Mode
,使用dplyr
很容易。
library(dplyr)
df %>%
group_by(CreditCardType, Bank, Year) %>%
summarise(mode = Mode(TotalBalance))
df
在哪里:
df <- read.table(text = 'CreditCardType Bank Year TotalBalance
MASTERCARD BOFA 2017 $100
MASTERCARD BOFA 2017 $100
MASTERCARD BOFA 2017 $700
VISA Wells 2018 $60
VISA Wells 2018 $50
VISA Wells 2018 $60', header = T, stringsAsFactors = F)
答案 1 :(得分:1)
这个问题obtaining 3 most common elements of groups, concatenating ties, and ignoring less common values
library(plyr)
getmode<- function(origtable,groupby,columnname) {
data <- ddply (origtable, groupby, .fun = function(xx){
c(m1 = paste(names(sort(table(xx[,columnname]),decreasing=TRUE)[1]))
) } )
return(data)
}
getmode(df,c("CreditCardType","Bank","Year"),"TotalBalance")
df<-read.table(text="CreditCardType Bank Year TotalBalance
MASTERCARD BOFA 2017 $100
MASTERCARD BOFA 2017 $100
MASTERCARD BOFA 2017 $700
VISA Wells 2018 $60
VISA Wells 2018 $50
VISA Wells 2018 $60", header=T, stringsAsFactors=F)
答案 2 :(得分:1)
另一种dplyr
解决方案:
df %>%
add_count(Credit_Card_Type, Bank, Year, Total_Balance) %>%
filter(n == max(n)) %>%
distinct() %>%
select(-n)
考虑关系并选择第一个模式值:
df %>%
add_count(Credit_Card_Type, Bank, Year, Total_Balance) %>%
filter(n == max(n)) %>%
distinct() %>%
select(-n) %>%
group_by(Credit_Card_Type, Bank, Year) %>%
summarise(Total_Balance = first(Total_Balance))
数据:
df <- read.table(text = "Credit_Card_Type Bank Year Total_Balance
MASTER_CARD BOFA 2017 100
MASTER_CARD BOFA 2017 100
MASTER_CARD BOFA 2017 700
VISA Wells 2018 60
VISA Wells 2018 50
VISA Wells 2018 60", header = TRUE)
答案 3 :(得分:1)
我找到了使用data.table和最适度的软件包的解决方案。
library(data.table)
library(modeest)
dt <- data.table("Type"=c(rep("MASTERCARD",3),rep("VISA",3)),"Bank"=c(rep("BOFA",3),rep("Wells",3)),"Year"=c(rep(2017,3),rep(2018,3)),"TotalBalance"=c(100,100,700,60,50,60))
dt[,mfv(TotalBalance)[1],by=c("Type","Bank","Year")]
Type Bank Year V1
1: MASTERCARD BOFA 2017 100
2: VISA Wells 2018 60