计算R中每个组中每个类别的百分比

时间:2016-10-28 08:22:13

标签: r

我有一个像这样的数据框

<!DOCTYPE html>

<html>

<head>
  <title>Modal example</title>
  <script src="js/modalise.js" type="text/javascript">
  </script>
  <script src="app.js" type="text/javascript">
  </script>
</head>

<body>
  <h1>Example modal 1</h1>
  <button id="openModal">Show the modal</button>
  <div class="modal-background">
    <form action="/etc/set_cookie.php" method="post">
      <div id="modal">
        <div class="modalconent tabs">
          <fieldset>
            <span class="close">×</span>
            <h2 class="fs-title">Cookies</h2>
            <h3 class="fs-subtitle">We use cookies to improve your experience</h3>
            <iframe style="width:100%; height:80px;" src="/etc/txt/cookies.php"></iframe>
            <br />
            <input type="submit" name="cookie" value="Accept" id="button" class="btn fr confirm" style="width:180px; padding:10px;" />
          </fieldset>
        </div>
      </div>
    </form>
  </div>
  <script>
    var myModal = {}

    window.onload = function() {
      // It is one of the button Modalise will attach the Show event.
      // Note that you can use Modalise without the events, by omitting the .attach() function.
      // Then, you can use show() or hide() to use it manually without overload. 
      var btnOpen = document.getElementById('openModal');

      // Modalise(id, options);
      myModal = new Modalise('exampleModal', {
          btnsOpen: [btnOpen]
        })
        .attach()
        .on('onShow', console.log)
        .on('onConfirm', console.log)
        .on('onHide', console.log);

    }
  </script>
</body>

</html>

我想介绍第四列,计算每组内每个类别的百分比。

Group    Category    Freq
1       A           2
1       B           3
1       C           5
2       A           3
2       B           1
2       C           6

我尝试了以下(没有成功)

Group    Category    Freq       % (calculated per group, for categories)
    1       A           2       20
    1       B           3       30
    1       C           5       50
    2       A           5       25
    2       B           1       5
    2       C           14      70

还有其他办法吗?

2 个答案:

答案 0 :(得分:4)

您可以使用dplyr

library(dplyr)
df <- data.frame(Group = c(1, 1, 1, 2, 2, 2), Category = c(LETTERS[1:3], LETTERS[1:3]), Freq = c(2, 3, 5, 5, 1, 14))
df %>% group_by(Group) %>% mutate(proc = (Freq/sum(Freq) * 100))

答案 1 :(得分:0)

我们可以使用dplyr

library(dplyr)
df1 %>% 
    group_by(Group) %>% 
    mutate(Percent = 100*Freq/sum(Freq))