order a dataframe according to a given list in R -
order a dataframe according to a given list in R -
this question has reply here:
order info frame rows according target vector specifies desired order 2 answersi have function calculate count of column in r want arrange dataframe entries according given list passed function
input appeared in form:
complete( c(2, 55, 8, 111, 12)) complete(30:25)
i have info frame in ascending order id, want arranged according list given
id nobs 2 463 8 586 12 338 55 711 111 932
should sorted / rearranged as:
id nobs 2 463 55 711 8 586 111 932 12 338
here's possible approach using merge :
# data.frame sort df <- read.csv(text= 'id,nobs 2,463 8,586 12,338 55,711 111,932') # keys utilize 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 data.frameid
contains values not nowadays in key
vector, go bottom of data.frame. in case of duplicated ids, kept adjacent after sorting. r
Comments
Post a Comment