Search code examples
rdataframesortingtablesorter

how to place a row by name up to the beginning of a data frame in r


I have this dataframe

a <- c(5, 7, 9, 11)
b <- c(-8, -10, -3, -1)
c <- c(-4, -1, -6, 3)
d <- c(-4, -1, -6, 3)
df <- t(data.frame(a,b,c, d))
    
   V1  V2   V3  V4
a   5   7   9   11
b   -8  -10 -3  -1
c   -4  -1  -6   3
d   -4  -1  -6   3

then I want the rest of the rows to keep the same order, just to set my desired row (by row name) to be in a certain position of my data frame.

for d to be in the second position i.e:

   V1  V2   V3  V4
a   5   7   9   11
d   -4  -1  -6   3
b   -8  -10 -3  -1
c   -4  -1  -6   3



for c to be in the first position i.e:

   V1  V2   V3  V4
c   -4  -1  -6   3
a   5   7   9   11
b   -8  -10 -3  -1
d   -4  -1  -6   3



Solution

  • We can create a function

    f1 <- function(dat, rownm, pos) {
        full_rnm <- row.names(dat)
        tmp <- full_rnm
        nm1 <- setdiff(full_rnm, rownm)
        rn <- seq_along(full_rnm)
        tmp[pos] <- rownm
        tmp[-pos] <- nm1
        dat[tmp, ]  
    }
    

    -testing

    > f1(df, "d", 2)
      [,1] [,2] [,3] [,4]
    a    5    7    9   11
    d   -4   -1   -6    3
    b   -8  -10   -3   -1
    c   -4   -1   -6    3
    
    > f1(df, "c", 1)
     [,1] [,2] [,3] [,4]
    c   -4   -1   -6    3
    a    5    7    9   11
    b   -8  -10   -3   -1
    d   -4   -1   -6    3