Sort a subset of columns for each row

后端 未结 3 1828
臣服心动
臣服心动 2021-01-16 19:44

I want to sort my.data[4:10] in descending order by row. Some clues here, but I could not parse it sufficiently: Sort second to fifth column for each row in R.

I al

相关标签:
3条回答
  • 2021-01-16 20:24

    This answer's approach, which you quote above, is close:

    cbind(df[,1], t(apply(df[,-1], 1, sort)))
    

    but it needed two changes:

    • You want to sort all but the first three columns, not all but the first. So change [,1] and [,-1] to [, 1:3] and [, -(1:3)], respectively.
    • By default, sort sorts in increasing order while you want decreasing order, and drops the NAs out entirely, while you want them last. You can fix this by adding the decreasing=TRUE, na.last=TRUE arguments to sort.

    This makes the solution:

    cbind(my.data[, 1:3], t(apply(my.data[, -(1:3)], 1, function(v) sort(v, decreasing=TRUE, na.last=TRUE))))
    

    Note that it might be a bit clearer if you split it onto multiple lines:

    mysort = function(v) sort(v, decreasing=TRUE, na.last=TRUE)
    sorted.cols = t(apply(my.data[, -(1:3)], 1, mysort))
    cbind(my.data[, 1:3], sorted.cols)
    
    0 讨论(0)
  • 2021-01-16 20:24

    This seems to work fine:

    my.data[,4:10] <- t(apply(my.data[,4:10], 1,  function(x) sort(x, na.last = T, decreasing=T)))
    
    
    #   habitat NumSites NumSamples Sp1 Sp2 Sp3 Sp4 Sp5 Sp6 Sp7
    #1    Marsh        3          6   3   1  NA  NA  NA  NA  NA
    #2  Prairie        3          5   2   2   2  NA  NA  NA  NA
    #3  Savanna        4          8  67   3   3   1  NA  NA  NA
    #4    Swamp        1          2   2  NA  NA  NA  NA  NA  NA
    #5 Woodland        4          8   2   1   1   1   1  NA  NA
    
    0 讨论(0)
  • 2021-01-16 20:26

    You don't need an anonymous function on this.

    > my.data[4:10] <-t(apply(my.data[4:10],1,sort,decreasing = TRUE,na.last = TRUE))
    > my.data
    #    habitat NumSites NumSamples Sp1 Sp2 Sp3 Sp4 Sp5 Sp6 Sp7
    # 1    Marsh        3          6   3   1  NA  NA  NA  NA  NA
    # 2  Prairie        3          5   2   2   2  NA  NA  NA  NA
    # 3  Savanna        4          8  67   3   3   1  NA  NA  NA
    # 4    Swamp        1          2   2  NA  NA  NA  NA  NA  NA
    # 5 Woodland        4          8   2   1   1   1   1  NA  NA
    
    0 讨论(0)
提交回复
热议问题