我有一个大型数据集,一列中包含多种产品,每种产品的信息包括过去几年的单位零售和每周数量。我正在尝试编写一个 for 循环,该循环按产品名称对数据进行子集化,并计算每个产品的行数的单位零售与数量之间的相关性。
我已经能够根据产品对数据进行子集化并计算相关性,但是有很多产品,实现一个循环来遍历每个独特的产品会更有益。
数据集示例:
`Category Label` `Fiscal Year` `Fiscal Week` `Net Sales` `Extended Quantity` `Unit Retail` `Log QTY` `Log Retail`
<chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 LOOSE CITRUS FY2018 FY2018-P01-W1 170833. 204901. 0.834 12.2 -0.182
2 LOOSE CITRUS FY2018 FY2018-P01-W2 158609. 187650. 0.845 12.1 -0.168
3 LOOSE CITRUS FY2018 FY2018-P01-W3 163580. 196313. 0.833 12.2 -0.182
4 LOOSE CITRUS FY2018 FY2018-P01-W4 146240. 185984. 0.786 12.1 -0.240
5 LOOSE CITRUS FY2018 FY2018-P02-W1 147494. 171036. 0.862 12.0 -0.148
6 LOOSE ONIONS FY2018 FY2018-P01-W1 88802. 78446. 1.13 11.3 0.124
7 LOOSE ONIONS FY2018 FY2018-P01-W2 77365. 66898. 1.16 11.1 0.145
8 LOOSE ONIONS FY2018 FY2018-P01-W3 88026. 75055. 1.17 11.2 0.159
9 LOOSE ONIONS FY2018 FY2018-P01-W4 114720. 97051. 1.18 11.5 0.167
10 LOOSE ONIONS FY2018 FY2018-P02-W1 95746. 82128. 1.17 11.3 0.153
#subset data into own df based on category
allProduce_split <- split(allProduce, allProduce$`Category Label`)
#correlation
cor_produce <- cor(allProduce_split$LOOSE CITRUS$`Unit Retail`,
allProduce_split$LOOSE CITRUS$`Extended Quantity`)
我希望有一个表,其中包含每个产品名称的单行,以及所有 5 个会计周的单位零售与数量之间的相关性,而不是仅仅返回示例中"LOOSE CITRUS 产品"的相关性。例如:
'Category Label' 'Cor'
LOOSE CITRUS .5363807
LOOSE ONIONS .6415218
product C .6498723
Product D -.451258
Product E .0012548
考虑类似于split
的by
,但随后允许使用第三个参数对子集应用任何函数。在您的情况下,您的函数可以构建产品标签和相关结果的数据框:
df_list <- by(allProduce, allProduce$`Category Label`, function(sub)
data.frame(product = sub$Category_Label[1],
cor_produce = cor(sub$`Unit Retail`,
sub$`Extended Quantity`)
)
)
final_df <- do.call(rbind, unname(df_list))
或者,您仍然可以使用该split
,但随后运行lapply
:
allProduce_split <- split(allProduce, allProduce$`Category Label`)
df_list <- lapply(allProduce_split, function(sub)
data.frame(product = sub$Category_Label[1],
cor_produce = cor(sub$`Unit Retail`,
sub$`Extended Quantity`)
)
)
final_df <- do.call(rbind, unname(df_list))
尝试:
library(dplyr)
df <-allProduce %>% group_by(Category Label) %>% mutate(correlation = cor(Unit Retail,Extended Quantity))