I want to re-arrange the rows of a dataframe that looks like this:
qs=c("q11", "q22", "q2", "q6", "q10")
ans=rep(1,times=length(qs))
df=data.frame(qs,ans)
arrange(df,qs)
qs ans
1 q10 1
2 q11 1
3 q2 1
4 q22 1
5 q6 1
However, I want the sorting of the rows to look in the much more logical order, such as this:
qs ans
1 q2 1
2 q6 1
3 q10 1
4 q11 1
5 q22 1
Can someone help me with this ?
Use R base:
df <- df[order(as.integer(gsub("q", "", as.character(df$qs)))), ]
For you example df, this gives:
qs ans
3 q2 1
4 q6 1
5 q10 1
1 q11 1
2 q22 1
You might note that rownames are not 1, 2, 3, 4, 5 after reordering; you can do:
rownames(df) <- 1:nrow(df)
to make it look nice:
qs ans
1 q2 1
2 q6 1
3 q10 1
4 q11 1
5 q22 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With