r语言 - 按其级别分解所有列,以及它们在我的数据集的属性中出现的次数



这是我的数据集,我想在数据集上完成对数据集的分解,其中包含文件每个属性的每个计数级别 这是我的代码:

library(dplyr)
#read File
h_Data<-read.csv(file.choose())
#store university attribute
h_Data<-h_Data$University
#Count each levels factor of data of 
h_DataDF <- data.frame(h_Data)
h_dataLevels<-h_DataDF %>% 
group_by(h_Data) %>%
summarise(no_rows = length(h_Data))
h_dataLevels  
#missing of data
h_DataMissing<-sum(is.na(h_Data))
h_DataMissing
#percentage of each level of factor
h_DataPer<-prop.table(table(h_Data))*100
#table format
h_DataTable <-data.frame(levels_data=h_dataLevels,levels_perc=h_DataPer,missing_data=h_DataMissing)
h_DataTable

我想总结为: levels_University no.of_timesLevels Percentage_of_Level缺失属性 IBA 4 57.14 0 KU 1 14.28 0 UIT 2 28.57 0

如果没有一些示例数据和所需的输出,很难确切知道您想要什么,但这里有一些代码,它采用一个数据帧,对于作为因子的每一列,返回一个数据帧,列出每个因子水平的观测值数。

## dummy data
df <- data.frame(Sex = c("m", "f", "m","f"), department = c("bs", "el", "bs", "se"), numbers = c(1,2,3,4))
## function that takes a column of data
## and returns factor counts if the column is a factor
countFactors <- function(col){
if(is.factor(col)){
fct_count(col)
}else{
NULL
}
}
## use purrr::map to iterate through the columns of the
## dataframe and apply the function
df %>% 
map(~ countFactors(.)) %>% 
compact()

最新更新