计算变量的频率

时间:2017-07-22 11:14:41

标签: r

我想将数据框(df)转换为不同的数据框(df1),其中df1的行对应于B列的出现频率({ {1}})。也就是说,在数据框df中,行中的值对应于它们在列{B}的列B中出现的次数,对于列的特定变量' A' df1。这是一个例子:

df

3 个答案:

答案 0 :(得分:4)

使用base-r中的table函数:

table(df)
#      B
# A    2011 2012 2013 2014
# 21    2    1    0    0
# 22    1    0    1    0
# 23    1    2    0    1

答案 1 :(得分:1)

<div class="modal text-xs-left" id="confirmBoxModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel33" aria-hidden="true">
<div class="modal-dialog modal-xs" role="document">
    <div class="modal-content">
        <div class="modal-body">
            <b>Are you sure ?</b>
        </div>
        <div class="modal-footer">
            <button class="btn btn-warning btn-xs" data-dismiss="modal"><i class="icon-cross2"></i> No</button>
            <button id="btnConfirmBoxDelete" type="submit" data-dismiss="modal" class="btn btn-primary btn-xs"><i class="icon-check2"></i> Yes</button>
        </div>

    </div>
</div>

输出

$(".deleteAgent").click(function (e) {

            var $buttonClicked = $(this);
            var id = $buttonClicked.attr('data-id');

            $('#confirmBoxModal').modal({
                backdrop: 'static',
                keyboard: false
            })
            .one('click', '#btnConfirmBoxDelete', function (e) {
                $.ajax({
                    type: "get",
                    url: 'url',
                    contentType: "application/json; charset=utf-8",
                    data: { "ID": id },
                    datatype: "json",
                    success: function (data) {
                        toastr.success('Agent Deleted Successfully!', null, { "closeButton": true });
                        location.reload();
                    },
                    error: function () {
                        alert("Something went Wrong contact Admin.");
                    },
                    beforeSend: function () {
                        $('#loadingDiv').show();
                    },
                    complete: function () {
                    }
                });
            });
        });

答案 2 :(得分:1)

使用dplyrtidyr

> library(tidyr)

输入:

> df <- read.csv(text="A,B
21,2011
21,2012
21,2011
22,2013
22,2011
23,2012
23,2011
23,2012
23,2014", header=T)    

小组,总结每个小组(tallysummarise(N = n())的简写)并传播到专栏(spread):

> df2 <- df %>% group_by(A,B) %>% tally %>% spread(B, n)
> df2[is.na(df2)] <- 0

输出:

> df2
# A tibble: 3 x 5
# Groups:   A [3]
      A `2011` `2012` `2013` `2014`
* <int>  <int>  <dbl>  <dbl>  <dbl>
1    21      2      1      0      0
2    22      1      0      1      0
3    23      1      2      0      1

或者,通过使用内置表函数并在之后使用tidyr传播(感谢用户C.Square):

> table(df) %>% data.frame %>% spread(B, Freq)
   A 2011 2012 2013 2014
1 21    2    1    0    0
2 22    1    0    1    0
3 23    1    2    0    1