在R中,如何在单个列中进行排序,以便一个类别是升序而一个是降序?

时间:2016-10-19 22:56:06

标签: r sorting

我正在生成不同大小和形状的多个实验设计。这是使用依赖agricolae包的函数完成的(我已将其包含在下面)。要为字段操作生成实际数据表,我需要按行对数据帧进行排序,然后对于奇数行对“范围”进行排序,对于“偶数行”对其进行排序。

使用sort,order,rep和seq我已经能够找到一个简单的解决方案。任何建议都非常感谢!

所以数据框将来自这样的东西:

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        mutation.addedNodes.forEach(function(addedNode) {
            if (addedNode.nodeName === 'HEAD') {
                var script = document.createElement('script');

                script.async = false;
                script.src = ('//third-party-js.com/third-party.js');

                addedNode.appendChild(script);
            }
        });
    });
});

observer.observe(document, {
    'childList': true,
    'subtree': true
});

对于这样的事情:

<script>

如果您感兴趣,这是试用设计功能。毫无疑问,这是一种更优雅的方式,但我并不是特别擅长R:

df1 <- structure(list(Block = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L), Range = c(1L, 2L, 3L, 4L, 1L, 2L, 
3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 
3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 
3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), Row = c(1L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 
5L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 
9L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L
), Plot = c(101L, 201L, 301L, 401L, 102L, 202L, 302L, 402L, 103L, 
203L, 303L, 403L, 104L, 204L, 304L, 404L, 105L, 205L, 305L, 405L, 
106L, 206L, 306L, 406L, 107L, 207L, 307L, 407L, 108L, 208L, 308L, 
408L, 109L, 209L, 309L, 409L, 110L, 210L, 310L, 410L, 111L, 211L, 
311L, 411L, 112L, 212L, 312L, 412L), Entry.Num = c(14L, 26L, 
18L, 4L, 52L, 17L, 41L, 47L, 40L, 30L, 21L, 12L, 9L, 2L, 8L, 
36L, 25L, 43L, 15L, 6L, 33L, 48L, 54L, 37L, 9L, 18L, 8L, 41L, 
48L, 28L, 7L, 47L, 54L, 38L, 46L, 23L, 19L, 1L, 3L, 27L, 36L, 
14L, 12L, 33L, 16L, 24L, 31L, 2L)), .Names = c("Block", "Range", 
"Row", "Plot", "Entry.Num"), class = "data.frame", row.names = c(NA, 
-48L))

1 个答案:

答案 0 :(得分:4)

order的魔力在等着你:

df1[order(df1$Row, c(-1,1)[df1$Row %% 2 + 1] * df1$Range ),]

基本上它的作用是按Row排序,然后按Range排序,如果是偶数则乘以-1x %% 2可用于检查奇数/偶数状态。

all.equal(
  df1[order(df1$Row, c(-1,1)[df1$Row %% 2 + 1] * df1$Range ),],
  df2,
  check.attributes=FALSE
)
#[1] TRUE