如何在R中将预测结果重塑为3×4格式的交叉表?
问题:如何在R中将预测结果重塑为交叉表格式
我编写了如下R代码:
v <- c("featureA", "featureB") newdata <- unique(data[v]) print(unique(data[v]) print(predict(model, newdata, type='response', allow.new.level = TRUE)
运行后得到featureA与featureB的唯一组合:
featureA featureB 1 bucket_in_10_to_30 bucket_in_90_to_100 2 bucket_in_10_to_30 bucket_in_50_to_90 3 bucket_in_0_to_10 bucket_in_50_to_90 4 bucket_in_0_to_10 bucket_in_90_to_100 7 bucket_in_10_to_30 bucket_in_10_to_50 10 bucket_in_30_to_100 bucket_in_90_to_100 19 bucket_in_0_to_10 bucket_in_0_to_10 33 bucket_in_0_to_10 bucket_in_10_to_50 36 bucket_in_30_to_100 bucket_in_10_to_50 38 bucket_in_10_to_30 bucket_in_0_to_10 52 bucket_in_30_to_100 bucket_in_0_to_10 150 bucket_in_30_to_100 bucket_in_50_to_90
以及对应的预测结果:
1 2 3 4 7 10 19 33 36 38 52 150 0.001920662 0.005480186 0.000961198 0.000335883 0.006311521 0.004005570 0.000620979 0.001107773 0.013100210 0.003546136 0.007382468 0.011384935
我希望将这些数据重塑为类似以下格式的3×4交叉表:
| feature A / features B | bucket_in_90_to_100 | bucket_in_50_to_90 |
|---|---|---|
| bucket_in_0_to_30 | ... | ... |
| bucket_in_30_to_100 | ... | ... |
解决方案
首先修正你代码中的语法错误(缺少闭合括号):
v <- c("featureA", "featureB") newdata <- unique(data[v]) print(unique(data[v])) print(predict(model, newdata, type='response', allow.new.level = TRUE))
接下来按以下步骤实现交叉表:
合并特征组合与预测结果
将特征组合数据框和预测值合并为一个完整的数据框:results_df <- cbind(newdata, prediction = predict(model, newdata, type='response', allow.new.level = TRUE))直接重塑为交叉表
使用tidyr包的pivot_wider函数将长格式数据转为宽格式交叉表:library(tidyr) cross_table <- pivot_wider(results_df, names_from = featureB, values_from = prediction)(可选)对featureA分组合并
如果你需要将bucket_in_0_to_10和bucket_in_10_to_30合并为bucket_in_0_to_30,可以先重编码分组再聚合:library(dplyr) # 重编码featureA分组 results_df <- results_df %>% mutate(featureA_group = case_when( featureA %in% c("bucket_in_0_to_10", "bucket_in_10_to_30") ~ "bucket_in_0_to_30", featureA == "bucket_in_30_to_100" ~ "bucket_in_30_to_100" )) # 按新分组聚合后重塑 cross_table_grouped <- results_df %>% group_by(featureA_group, featureB) %>% summarise(prediction = mean(prediction)) # 可根据需求替换为sum等聚合方式 %>% pivot_wider(names_from = featureB, values_from = prediction)
运行上述代码后,即可得到符合需求的交叉表格式数据。
内容的提问来源于stack exchange,提问作者Kyle
相关产品推荐
相关产品推荐

