我有一个包含四列数据的数据集。
我希望按两个变量对行进行分组,将列分组为一个变量
以下是我的数据示例
df <- data.frame(
Price = rnorm(24),
Grouping = rep(c("CD", "NW", "SMK", "ghd"),6),
Sub_grouping = c("CDapple", "NWapple", "SMKapple", "ghdapple",
"CDPear", "NWpear", "SMKpear", "ghdpear",
"CDgrape", "NWgrape", "SMKgrape", "ghdgrape",
"CDapple", "NWapple", "SMKapple", "ghdapple",
"CDPear", "NWpear", "SMKpear", "ghdpear",
"CDgrape", "NWgrape", "SMKgrape", "ghdgrape"),
SP = rep(c("SP", "OffSP"),12))
要获得每个子组的Price变量的平均值,我可以运行以下命令:
df <- melt(df)
df_mean <- dcast(df, Grouping + Sub_grouping ~ SP, value.var = "value", fun.aggregate = mean)
我还想要每个分组变量的平均价值。这可能吗?
我还想计算每个平均价格的价格数量。因此,对于每个集团,由SP和OffSP,为此提供的价格数量;对于每个子组,按SP和OffSP,为此提供的价格数量。
有谁知道怎么做?
我已经看到了这些问题Create a column with a count of occurrences in R How can I count the number of instances a value occurs within a subgroup in R? 但是它们的列联表是2x2,我需要一个表,其中分组和子组为行,SP / OffSP为列。
由于
答案 0 :(得分:2)
我们不需要将其重塑为“长期”。格式以获取mean
值
library(dplyr)
df %>%
group_by(Grouping) %>% #first grouping
#create the mean column and the count by 'Grouping'
mutate(AvgPrice = mean(Price), n1 = n()) %>%
group_by(Sub_grouping, add= TRUE) %>% #second grouping
#summarise to get the mean within Sub_grouping and count the values with n()
summarise(AvgPrice = first(AvgPrice), n1 = first(n1), AvgPrice2 = mean(Price), n2 = n())
注意:如果我们还需要按&#39; SP&#39;进行分组,请将第一个group_by
语句更改为
df
%>%
group_by(Grouping, SP) %>%
...
...
如果我们希望获得每个&#39; SP&#39;的mean
和length
并希望作为单独的列,一个紧凑的选项dcast
来自data.table
,可以使用多个函数和多个value.var
列
library(data.table)
dcast(setDT(df), Grouping + Sub_grouping ~ SP, value.var = "Price", c(mean, length))