2

I have a function where i calculate count of a column in R
I want to arrange my dataframe entries according to a given list passed to a function

input appeared in this form:

complete( c(2, 55, 8, 111, 12))
complete(30:25)

I have my data frame in ascending order by id, i want it to be arranged according to list given

id   nobs
2    463
8    586
12   338
55   711
111  932

Should be sorted / rearranged as:

id   nobs
2    463
55   711
8    586
111  932
12   338
rawr
  • 20,481
  • 4
  • 44
  • 78
  • you don't have to order them, this is just indexing. at the end of your `complete` function, have it return the data frame, `df`, as `df[df$id %in% x, ]` where x is the arg given to `complete` – rawr Oct 24 '14 at 21:37

1 Answers1

1

Here's a possible approach using merge :

# data.frame to sort
DF <- 
read.csv(text=
'id,nobs
2,463
8,586
12,338
55,711
111,932')

# keys to use for sorting
keys <- c(2, 55, 8, 111, 12)

keyDF <- data.frame(key=keys,weight=1:length(keys))

merged <- merge(DF,keyDF,by.x='id',by.y='key',all.x=T,all.y=F)
res <- merged[order(merged$weight),c('id','nobs')]

> res
   id nobs
1   2  463
4  55  711
2   8  586
5 111  932
3  12  338

N.B.

  • in case your data.frame id contains values not present in the key vector, those will go to the bottom of the data.frame.
  • in case of duplicated ids, they will be kept adjacent after sorting.
digEmAll
  • 56,430
  • 9
  • 115
  • 140