根据R中的排名减少变量(列)的顺序

时间:2016-05-03 09:31:13

标签: r

我有一个数据框,对3个变量a,b和c

有一些非负值(排序类型)
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject jo = response.getJSONObject("data");
                    name=jo.toString();
                    ids.add(name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, ids));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        rq = Volley.newRequestQueue(this);
        rq.add(jsonObjectRequest);

我想计算一个新变量&#34; 优先级&#34;它给出了应该选择变量的优先级

x <- data.frame(cbind(ID=c(1,2,3,4,5),a=c(14,20,0,14,0),b=c(20,0,20,12,0),c=c(12,12,0,0,20)))

+----------------+
|ID  | a | b | c |
+----------------+
|1   |14 |20 |12 |
|2   |20 |0  |12 |
|3   |0  |20 |0  |
|4   |14 |12 |0  |
|5   |0  |0  |20 |
+----------------+

有关如何在R中创建此类输出的任何帮助都深受赞赏。

3 个答案:

答案 0 :(得分:2)

这是尝试使用长格式然后加入到原始数据集

的尝试
library(data.table) 
indx <- melt(setDT(x), 1L)[value > 0, 
             paste(variable[order(-value)], collapse = ">"), 
             by = ID]
x[indx, priority := i.V1, on = "ID"]
x
#    ID  a  b  c priority
# 1:  1 14 20 12    b>a>c
# 2:  2 20  0 12      a>c
# 3:  3  0 20  0        b
# 4:  4 14 12  0      a>b
# 5:  5  0  0 20        c

这基本上是“融化”数据ID,过滤大于零的值,按ID分配/粘贴列名

答案 1 :(得分:0)

这样吗?

apply(x[-1], 1, function(x) paste(names(x)[x!=0][order(x[x!=0], 
    decreasing = T)], collapse = ">"))
[1] "b>a>c" "a>c"   "b"     "a>b"   "c"  

答案 2 :(得分:0)

colLabels=c("a","b","c")
sorting=function(x){
      sortedInd = (sort.int(x, index.return = TRUE, decreasing = TRUE))$ix
      sortedLabels = colLabels[sortedInd]
      paste(sortedLabels, collapse = ">")
}

x$priority = apply(x[,-1],1,sorting)

sortedInd返回每个已排序行的索引,然后将其输入colLabels以获取相应的标签。然后使用折叠将标签组合为“&gt;”在粘贴