Home > Mobile >  How to move two specific rows to top of dataframe?
How to move two specific rows to top of dataframe?

Time:01-07

Below I have a DF.

A   B   C   D
a   4   2   2
g   5   2   2  
d   7   65  7
e   3   6   7

I would like to make this DF so that column A has "g" in the first row, and "d" in the second row. I would like to do this by calling the value in column A (rather than an index). How can I do this?

Ideal output

A   B   C   D
g   5   2   2  
d   7   65  7
a   4   2   2
e   3   6   7

CodePudding user response:

We may convert to factor with levels specified in an order before arrangeing

library(forcats)
library(dplyr)
DF %>% 
   arrange(fct_relevel(A, 'g', 'd'))
  A B  C D
1 g 5  2 2
2 d 7 65 7
3 a 4  2 2
4 e 3  6 7

with fct_relevel, we can specify the order of specific levels without specifying the rest of the levels

> with(DF, fct_relevel(A, 'g', 'd'))
[1] a g d e
Levels: g d a e

data

DF <- structure(list(A = c("a", "g", "d", "e"), B = c(4L, 5L, 7L, 3L
), C = c(2L, 2L, 65L, 6L), D = c(2L, 2L, 7L, 7L)), class = "data.frame",
 row.names = c(NA, 
-4L))

CodePudding user response:

Another possible solution:

library(dplyr)

df <- data.frame(
  stringsAsFactors = FALSE,
  A = c("a", "g", "d", "e"),
  B = c(4L, 5L, 7L, 3L),
  C = c(2L, 2L, 65L, 6L),
  D = c(2L, 2L, 7L, 7L)
)

df %>% arrange(match(A, c("g", "d", setdiff(c("g", "d"), A))))

#>   A B  C D
#> 1 g 5  2 2
#> 2 d 7 65 7
#> 3 a 4  2 2
#> 4 e 3  6 7

CodePudding user response:

Just to add a base R solution if you are not interested in external packages, you can specify the row order directly:

# Sample Data
DF <- structure(list(A = c("a", "g", "d", "e"), B = c(4L, 5L, 7L, 3L
), C = c(2L, 2L, 65L, 6L), D = c(2L, 2L, 7L, 7L)), class = "data.frame",
row.names = c(NA, -4L))

A hard code for this example:

DF2 <- DF[c(2,3,1,4),]

A more generalizable example:

# specify desired rows
rownums <- which(DF$A %in% c("g","d"), arr.ind = TRUE)

# Specify other rows
otherrows <- seq(1:nrow(DF))[!(seq(1:nrow(DF)) %in% rownums)]

# Organize
DF2 <- DF[c(rownums,otherrows),]

CodePudding user response:

Try the code below

with(
  df,
  df[match(c("g","d",A[!A%in%c("g","d")]),A),]
)

and you will see

  A B  C D
2 g 5  2 2
3 d 7 65 7
1 a 4  2 2
4 e 3  6 7
  •  Tags:  
  • Related