Michael
Michael

Reputation: 575

Reorder column conditional on another column in R

Consider the following data frame in R:

d <- data.frame(c("e204030","d405054",""),c("d405054","s304020","e204030"),
                c("val1020","val1030","val1040"))

I want to reorder column two based on column one, so I get the following data frame:

1:  e204030 e204030  val1040
2:  d405054 d405054  val1020
3:          s304020  val1030

How do I do that in R? As you can see there is one value (s304020) where it cannot find a match in column one, so that row should just be placed at the bottom.

Upvotes: 1

Views: 80

Answers (2)

Michael
Michael

Reputation: 575

I found the following solution:

reorder_idx <- match(d$a,d$b)

e <- d

e$b <- e$b[reorder_idx]
e$c <- e$c[reorder_idx]

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

A way using base R :

#Create a copy of dataframe
e <- d
#Get the row indices which match
inds <- na.omit(match(d$a,d$b))
#Assign the match rows
e[seq_along(inds), -1] <- d[inds, -1] 
#assign the rows which do not match
e[(length(inds) + 1):nrow(e),-1] <- d[setdiff(seq_len(nrow(d)), inds), -1]
e
#        a       b       c
#1 e204030 e204030 val1040
#2 d405054 d405054 val1020
#3         s304020 val1030

data

d <- data.frame(a = c("e204030","d405054",""),
                b = c("d405054","s304020","e204030"),
                c = c("val1020","val1030","val1040"))

Upvotes: 1

Related Questions