在R中创建数据透视表

时间:2016-08-04 11:55:29

标签: r pivot-table percentage

我知道这已被多次询问过,但我在过去2天内滚动了互联网,无法找到创建数据透视表或汇总表所需的帮助,就像我可以用excel做的那样。我对R完全是一个完全文盲的新手,所以我发现R包中的大多数例子帮助文件过于复杂。

我有一个看起来像这样的数据列表(“​​集合”)

$filename_path = md5(time().uniqid()).".jpg";
$base64_string = str_replace('data:image/png;base64,', '', $base64_string);
$base64_string = str_replace(' ', '+', $base64_string);
$decoded = base64_decode($base64_string);
file_put_contents("uploads/".$filename_path,$decoded);

我已经设法使用dcast()

做了一个像表一样的摘要/ pivottable
Phase   class  NISP
   <chr>   <chr> <int>
1      L    Aves    11
2      L    Fish   128
3      L Mammals    14
4      K    Aves    63
5      K    Fish    30
6      K Mammals   311
7      J    Aves   170
8      J    Fish   327
9      J Mammals   740
10     I    Aves    45
# ... with 18 more rows

具有以下结果

pivot <-dcast(assemblage, Phase ~ class, fun.aggregate = sum, value.var = "NISP", margins = TRUE)

但我现在需要的是我无法弄清楚的是:

  • 用“总计”替换(全部)
  • 按以下顺序排列列(“阶段”,“哺乳动物”,“鱼”,“Aves”,“不确定”,“总计”)
  • 添加每个阶段每个动物类别百分比的新列(行总百分比)。

1 个答案:

答案 0 :(得分:0)

下面的代码应该一步一步地完成所有事情。如果有什么不清楚,请告诉我。

Sub MergeMultiSheets()

Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim Path As String
Dim Filename As String

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False

Path = "C:\Users\*ChangeThis*\Desktop\merge"    

Set wbDst = Workbooks.Add(xlWBATWorksheet)
Filename = Dir(Path & "\*.xlsx", vbNormal)

If Len(Filename) = 0 Then Exit Sub

Do Until Filename = ""
    Set wbSrc = Workbooks.Open(Filename:=Path & "\" & Filename)

    Sheet = 1
    ' ****** you need to loop on all sheets per Excel workbook found in Folder ******
    For Each wsSrc In wbSrc.Sheets        
        wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)        
    Next wsSrc

    wbSrc.Close False
    Filename = Dir()
Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub