简体   繁体   English

计算数据框中所有非数字列的模式

[英]Calculate the mode of all non-numeric columns in a dataframe

I would like to calculate the mode of each column from a dataframe. 我想从数据框中计算每一列的模式。 I have found similar posts on how to determine the mode of a vector of rows in a dataframe (but most have been with numeric data). 我发现了有关如何确定数据帧中行向量的模式的类似文章(但大多数都是关于数字数据的)。

df <- data.frame(c("A","B","C","C"), c("A","A","B","C"),c("A","B","B","C"))
colnames(df) <- c("V1","V2","V3")
rownames(df) <- c(1,2,3,4)
df

I am using the following function: 我正在使用以下功能:

modefunc <- function(x){
    tabresult <- tabulate(x)
    themode <- which(tabresult == max(tabresult))
    if(sum(tabresult == max(tabresult))>1) themode <- NA
    return(themode)
}

mode.vector <- apply(df, 1, modefunc)

Since my dataframe is not numeric, I unfortunately get the following error: 由于我的数据框不是数字的,因此很不幸出现以下错误:

Error in tabulate(x) : 'bin' must be numeric or a factor

Any assistance with this would be helpful. 任何与此有关的帮助都会有所帮助。 Thanks in advance. 提前致谢。

I changed your function a little. 我稍微改变了你的功能。

modefunc <- function(x){
  x<-c(as.character(x) ,use.names = F,  recursive = TRUE )
  tabresult <- table(x)
  mod<-sort(table(x),decreasing = T)[1]
  mod_name<-names(mod)
  if(sum(tabresult == mod)>1) themode <- NA
  return(mod_name)
}

mode.vector <- apply(df, 1, modefunc)
 1   2   3   4 
"A" "B" "B" "C" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM