R:遍历for循环以打印多个表



在房价预测数据集中,大约有80个变量和1459个obs。
为了更好地理解数据,我分离了"char"类型的变量。

char_variables = sapply(property_train, is.character)  
char_names = names(property_train[,char_variables])  
char_names

有42个变量是char数据类型
我想找出每个变量中的观测次数
简单的代码是:

table(property_train$Zoning_Class)  
Commer    FVR    RHD    RLD    RMD 
10     65     16   1150    218

但是,对42个变量重复同样的操作将是一项乏味的任务
我尝试打印所有表格的for循环显示错误。

for (val in char_names){  
print(table(property_train[[val]]))
}

Abnorml AdjLand  Alloca  Family  Normal Partial 
101       4      12      20    1197     125 

有没有一种方法可以在数据帧中迭代char_names来打印所有42个表。

str(property_train)
'data.frame':   1459 obs. of  81 variables:  
$ Id                       : int  1 2 3 4 5 6 7 8 9 10 ...  
$ Building_Class           : int  60 20 60 70 60 50 20 60 50 190 ...  
$ Zoning_Class             : chr  "RLD" "RLD" "RLD" "RLD" ...  
$ Lot_Extent               : int  65 80 68 60 84 85 75 NA 51 50 ...  
$ Lot_Size                 : int  8450 9600 11250 9550 14260 14115 10084 10382..   
$ Road_Type                : chr  "Paved" "Paved" "Paved" "Paved" ...  
$ Lane_Type                : chr  NA NA NA NA ...  
$ Property_Shape           : chr  "Reg" "Reg" "IR1" "IR1" ...  
$ Land_Outline             : chr  "Lvl" "Lvl" "Lvl" "Lvl" ...  

实际上,对我来说,你的代码没有给出错误(确保一起评估for循环中的所有行(:

property_train <- data.frame(a = 1:10,
b = rep(c("A","B"),5),
c = LETTERS[1:10])
char_variables = sapply(property_train, is.character)
char_names = names(property_train[,char_variables])
char_names
table(property_train$b)
for (val in char_names){
print(table(property_train[val])) 
}

您还可以使用dplyr和tidyr,通过将所有字符列转换为长格式并计算所有列值组合,以更用户友好的形式获得此结果:

library(dplyr)
library(tidyr)
property_train %>% 
select(where(is.character)) %>% 
pivot_longer(cols = everything(), names_to = "column") %>% 
group_by(column, value) %>% 
summarise(freq = n())

最新更新