具有第三个变量 R 的均值的双向 table

Two way table with mean of a third variable R

这是我的问题。我有一个 table,我在这里展示了一个示例。我希望将国家/地区作为行,将星星作为列,并将每种组合的价格均值。我使用了聚合,它给了我想要的信息,但不是我想要的信息。

table 看起来像这样:

    Country Stars Price
1   Canada     4   567
2    China     2   435
3   Russia     3   456
4   Canada     5   687
5   Canada     4   432
6   Russia     3   567
7    China     4  1200
8   Russia     3   985
9   Canada     2   453
10  Russia     3   234
11  Russia     4   546
12  Canada     3   786
13   China     2   456
14   China     3   234
15  Russia     4   800
16   China     5   987

我使用了这个代码:

aggregate(Stars[,3],list(Country=Stars$Country, Stars = Stars$Stars), mean)

输出:

   Country Stars      x
1   Canada     2  453.0
2    China     2  445.5
3   Canada     3  786.0
4    China     3  234.0
5   Russia     3  560.5
6   Canada     4  499.5
7    China     4 1200.0
8   Russia     4  673.0
9   Canada     5  687.0
10   China     5  987.0

其中 x 代表平均值,我想将“价格平均值”的 x 更改为... 因此,目标是每行一个国家,星星的数量作为列,每对的价格均值。

非常感谢。

您似乎希望 Excel 像枢轴 table 一样。这里包pivottablerhelps much。看,它也生成不错的 html tables(除了显示结果)

library(pivottabler)
qpvt(df, "Country", "Stars", "mean(Price)")

        2      3                 4      5    Total     
Canada    453               786  499.5  687       585  
China   445.5               234   1200  987     662.4  
Russia                    560.5    673            598  
Total     448  543.666666666667    709  837  614.0625

格式化使用format参数

qpvt(df, "Country", "Stars", "mean(Price)", format = "%.2f")
        2       3       4        5       Total   
Canada  453.00  786.00   499.50  687.00  585.00  
China   445.50  234.00  1200.00  987.00  662.40  
Russia          560.50   673.00          598.00  
Total   448.00  543.67   709.00  837.00  614.06 

对于 html 输出使用 qhpvt 代替。


qhpvt(df, "Country", "Stars", "mean(Price)")

输出

注意:tidyversebaseR方法也是可行的,也很简单

获取two-waytable的方法,附加数据后可以使用

tapply(Price, list(Country,Stars), mean)