gpt4 book ai didi

r - 按分类数据分组的零售价格汇总统计

转载 作者:行者123 更新时间:2023-12-02 18:14:45 24 4
gpt4 key购买 nike

我需要一些帮助来编写一个函数,该函数接受三个分类输入并根据这些输入返回一个汇总统计向量。

该数据集包含有关零售商品的信息,可以通过其零售部门、品牌名称、商品类型及其零售价格和实际售价来指定。

现在我需要编写一个函数来获取这些输入并求平均值、计数并计算其他需要的内容。

我已将函数设置如下(使用虚构数据):

dataold = data.frame(segment=c("golf","tenis","football","tenis","golf","golf"),
brand=c("x","y","z","y","x","a"),
type=c("iron","ball","helmet","shoe","driver","iron"),
retail=c(124,.60,80,75,150,108),
actual=c(112,.60,72,75,135,100))

retailsum = funtion(segment,brand,type){
datanew = dataold[which(dataold$segment='segment' &
dataold$brand='brand' &
dataold$type='type'),c("retail","actaul")]

summary = c(dim(datanew)[1],colMeans(datanew))
return(summary)
}

函数大括号内的代码可以独立工作,但是一旦我将函数包裹在它周围,我就会开始收到错误,或者它只会返回 0 计数和 NaN手段。

任何帮助将不胜感激。我对 R 的经验很少,所以如果这是一个微不足道的问题,我深表歉意,但我一直无法找到解决方案。

最佳答案

您的代码中有很多错误,包括:

  • 函数拼写错误
  • 使用单个 =(赋值)而不是 ==(相等测试)
  • 实际输入错误
  • 在函数中对segmentbrandtype进行硬编码,而不是引用参数。

这就是您的函数的样子,即它产生有效的结果:

retailsum <- function(data, segment,brand,type, FUN=colMeans){    
x = with(data, data[segment==segment && brand==brand && type==type,
c("retail","actual")])
match.fun(FUN)(x)
}

retailsum(dataold, "golf", "x", "iron", colMeans)
retail actual
89.60000 82.43333
<小时/>

这是一个使用 plyr 包的(可能更灵活)解决方案。这将计算分割市场、品牌和类型的所有组合的函数:

library(plyr)
ddply(dataold, .(segment, brand, type), colwise(mean))
segment brand type retail actual
1 football z helmet 80.0 72.0
2 golf a iron 108.0 100.0
3 golf x driver 150.0 135.0
4 golf x iron 124.0 112.0
5 tenis y ball 0.6 0.6
6 tenis y shoe 75.0 75.0

关于r - 按分类数据分组的零售价格汇总统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10570087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com