2016-05-10 4 views
0

У меня есть вектор строк, каждый из которых имеет число внутри, и мне нравится сортировать этот вектор в соответствии с этим числом.порядковые строки в соответствии с некоторыми символами

MWE:

> str = paste0('N', sample(c(1,2,5,10,11,20), 6, replace = FALSE), 'someotherstring') 
> str 
[1] "N11someotherstring" "N5someotherstring" "N2someotherstring" "N20someotherstring" "N10someotherstring" "N1someotherstring" 
> sort(str) 
[1] "N10someotherstring" "N11someotherstring" "N1someotherstring" "N20someotherstring" "N2someotherstring" "N5someotherstring" 

в то время как я хотел бы иметь

[1] "N1someotherstring" "N2someotherstring" "N5someotherstring" "N10someotherstring" "N11someotherstring" "N20someotherstring" 

Я думал использовать что-то вроде:

num = sapply(strsplit(str, split = NULL), function(s) { 
    as.numeric(paste0(head(s, -15)[-1], collapse = "")) 
}) 
str = str[sort(num, index.return=TRUE)$ix] 

, но я предполагаю, что там может быть что-то проще

ответ

3

Существует простой способ сделать это через gtools package,

gtools::mixedsort(str) 
#[1] "N1someotherstring" "N2someotherstring" "N5someotherstring" "N10someotherstring" "N11someotherstring" "N20someotherstring" 
+1

спасибо! Я был уверен, что есть что-то еще ... – clemlaflemme

+0

Ищем другие манипуляции с строками, я просто получил еще один трюк: 'ind = sort (as.numeric (gsub ('[AZ, az]', '', str)), index .return = TRUE) ' – clemlaflemme

+0

@clemlaflemme да есть несколько способов сделать это. – Sotos

Смежные вопросы