0

Been trying to find the answer to this question and haven't been able to. Say I have the dataframe,

DF <- data.frame (x=c("2,A","1,A","1,C", "1,B"), y = c(1,2,2,1))

yielding a Dataframe with two columns, the first of which has a number and a letter. How can I sort DF according to the number part of each of its rows? And then, add to it another column only with the letter. The objective is to obtain,

    x y z
1 1,A 2 A
2 2,A 1 A
3 1,B 1 B
4 1,C 2 C

Cheers

1 Answer 1

2

Use gsub to replace all digits or comma ("(\\d+|,)") and all non-digits ("\\D+") successively and then use order to sort DF based on that.

DF = DF[order(as.character(gsub("(\\d+|,)", "", DF$x)), as.numeric(gsub("\\D+", "", DF$x))),]
DF$z = gsub("(\\d+|,)", "", DF$x)
DF
#    x y z
#2 1,A 2 A
#1 2,A 1 A
#4 1,B 1 B
#3 1,C 2 C
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic. Thanks for the answer and the general tip on handling digits and strings! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.