R编程:如何根据另一列的值删除列中的重复项

时间:2017-07-19 05:54:16

标签: r

A   B
15  O
20  O
12  C
15  C
50  C
25  O
50  O
19  O
50  M

我有上述格式的数据。 我想根据A列中的唯一元素选择唯一的行 但是如果有重复,那么我需要参考B列并选择代码为'C'的那个

预期产出:

A   B
20  O
12  C
15  C
50  C
25  O
19  O

任何人都可以提供帮助..

1 个答案:

答案 0 :(得分:1)

我们可以使用data.table。根据逻辑条件(setDT(df1))将'data.frame'转换为'data.table'(order),按'A',B==O分组,然后获取第一行与head

library(data.table)
setDT(df1)[order(B=="O"), head(.SD, 1), A]
#    A B
#1: 12 C
#2: 15 C
#3: 50 C
#4: 20 O
#5: 25 O
#6: 19 O

或者可以base R order unique来完成此操作,并使用duplicated

获取df2 <- df1[order(df1$A, df1$B=="O"),] df2[!duplicated(df2$A),] 个元素
<!DOCTYPE html>
<html>

<head>
    <script src="bower_components/vss-web-extension-sdk/lib/VSS.SDK.min.js"></script>
    <script type="text/javascript">
VSS.init({
        explicitNotifyLoaded: true,
        usePlatformStyles: true 
    });

VSS.require([
        "TFS/Dashboards/WidgetHelpers", 
        "Charts/Services"
        ],
        function (WidgetHelpers, Services) {
        WidgetHelpers.IncludeWidgetStyles();
        VSS.register("SimplePieChart", function () { 
             return {
             load:function() {
                return Services.ChartsService.getService().then(function(chartService){
                    var $container = $('#Chart-Container');
                    var chartOptions = { 
                        "hostOptions": { 
                            "height": "290", 
                            "width": "300"
                        },
                        "chartType": "pie",
                        "series": [{
                            "data": [11, 4, 3, 1]
                        }],
                        "xAxis": { 
                            "labelValues": ["Design", "On Deck", "Completed", "Development"] 
                        }, 
                        "specializedOptions": {
                            "showLabels": "true",
                            "size": 200
                        } 
                    };

                    chartService.createChart($container, chartOptions);
                    return WidgetHelpers.WidgetStatusHelper.Success();
                });
                }
             }
            });
    VSS.notifyLoadSucceeded();
});
</script>
</head>

<body>
    <div class="widget">
        <h2 class="title">Chart Widget</h2>
        <div id="Chart-Container"></div>
    </div>
</body>

</html>