R语言data.table函数调用无返回输出问题求助
解决data.table函数无返回结果的问题
排查步骤与解决方案
先确认调用方式
你是不是直接运行genderspend(monthtrans_dat, products_dat, customers_dat)而没把结果赋值给变量?R函数默认会返回最后一行的对象,但如果不赋值,在脚本环境里可能不会自动打印。试试:# 赋值后再查看结果 gender_result <- genderspend(monthtrans_dat, products_dat, customers_dat) gender_result调整函数加载逻辑
把require(data.table)移到函数外面,函数内重复加载没必要,而且如果加载失败只会返回FALSE不会报错,可能导致后续data.table语法失效:# 先在全局环境加载data.table library(data.table) genderspend <- function(monthtrans_dat, products_dat, customers_dat) { setDT(monthtrans_dat) setDT(products_dat) setDT(customers_dat) tab.revenue <- merge(monthtrans_dat, products_dat[, .(product_id, category)], by="product_id") tab.revenue[, revenue := price*quantity] tab.ordercustomers <- merge(tab.revenue, customers_dat, by = "customer_id") tab.genderspend <- tab.ordercustomers[, .(total_spend = sum(revenue)), by = "gender"] tab.genderspend[, percentage := 100*(total_spend/sum(total_spend))] tab.genderspend }另外,如果传入的参数已经是data.table类型,
setDT可以直接省略,它主要用于将data.frame转换为data.table。验证中间步骤数据状态
可以在函数里临时添加打印语句,排查哪一步出现异常:genderspend <- function(monthtrans_dat, products_dat, customers_dat) { library(data.table) setDT(monthtrans_dat) setDT(products_dat) setDT(customers_dat) tab.revenue <- merge(monthtrans_dat, products_dat[, .(product_id, category)], by="product_id") cat("tab.revenue行数:", nrow(tab.revenue), "\n") # 检查商品关联后是否有数据 tab.revenue[, revenue := price*quantity] tab.ordercustomers <- merge(tab.revenue, customers_dat, by = "customer_id") cat("tab.ordercustomers行数:", nrow(tab.ordercustomers), "\n") # 检查客户关联后是否有数据 tab.genderspend <- tab.ordercustomers[, .(total_spend = sum(revenue)), by = "gender"] cat("tab.genderspend内容:\n") print(tab.genderspend) tab.genderspend[, percentage := 100*(total_spend/sum(total_spend))] tab.genderspend }如果某一步输出行数为0,说明你的数据集关联键(
product_id、customer_id)没有匹配上,要检查传入函数的数据集是否和外部测试时的一致。
代码优化建议
用data.table的链式操作简化代码,更高效也更易读:
library(data.table) genderspend <- function(monthtrans_dat, products_dat, customers_dat) { setDT(monthtrans_dat) setDT(products_dat) setDT(customers_dat) monthtrans_dat[products_dat[, .(product_id, category)], on = "product_id"] %>% .[, revenue := price * quantity] %>% .[customers_dat, on = "customer_id"] %>% .[, .(total_spend = sum(revenue)), by = gender] %>% .[, percentage := 100 * (total_spend / sum(total_spend))] }
内容的提问来源于stack exchange,提问作者amatof
相关产品推荐
相关产品推荐

