Jj Blevins
Jj Blevins

Reputation: 395

R: reordering columns based on order of different column

I have the following data:

x  y   id
1  2      
2  2    1
3  4    
5  6    2
3  4  
2  1    3

The blanks in column id should have the same values as the next id value. Meaning my data should actually look like this:

x  y   id
1  2    1  
2  2    1
3  4    2
5  6    2
3  4    3
2  1    3

I also have a list:

list[[1]] = 1 3 2

Or alternatively a column:

c(1,3,2) = 1, 3, 2

Now I would like to reorder my data based on column id accroding to the order in the list. My data should like this then:

x  y   id
1  2   1   
2  2   1 
3  4   3
2  1   3
3  4   2
5  6   2

Is there an efficient way to do this?

EDIT: I don't think it is a duplicate of in R Sorting by absolute value without changing the data because I do no want to sort by absolute value but by specific order that is given in a list.

Upvotes: 2

Views: 285

Answers (1)

akrun
akrun

Reputation: 887118

A base R option would be (assuming that the blanks in 'id' column is NA)

i1 <- !is.na(df1$id)
df1[i1,][match(df1$id[i1], list[[1]]),] <- df1[i1, ]
df1
#  x y id
#1 1 2 NA
#2 2 2  1
#3 3 4 NA
#4 2 1  3
#5 3 4 NA
#6 5 6  2

If we need to change the NA to succeeding non-NA element

library(zoo)
df1$id <- na.locf(df1$id, fromLast = TRUE)

data

df1 <- structure(list(x = c(1L, 2L, 3L, 5L, 3L, 2L), y = c(2L, 2L, 4L, 
 6L, 4L, 1L), id = c(NA, 1L, NA, 2L, NA, 3L)), class = "data.frame", 
 row.names = c(NA, -6L))

Upvotes: 3

Related Questions