根据字符列对数据框进行排序,该字符列包含字母,后跟R中的数字 [英] Sort a dataframe based on a character column containing letters followed by numbers in R

查看:545
本文介绍了根据字符列对数据框进行排序,该字符列包含字母,后跟R中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框

I have a dataframe like this

Day <- c("Day1","Day20","Day5","Day10")
A <- c (5,7,2,0)
B <- c(15,12,16,30)

df <- data.frame(Day,A,B)

df$Day <- as.character(df$Day)

第一列是一个字符,因此我使用了

The first column is a character and hence I used this solution to sort this dataframe but not quite getting it right since this only sorts the first column and leaves the column 2 & 3 unchanged.

df$Day <- df$Day[order(nchar(df$Day), df$Day)]

我想要的输出是

 Day A  B
Day1 5 15
Day5 2 16
Day10 0 30
Day20 7 12

我在这里想念什么?请提供一些输入.

What am I missing here? Kindly provide some inputs.

推荐答案

您可以尝试使用类似的方法进行数字日排序:

You can try using something like this that does numeric day sorting:

Day <- c("Day1","Day20","Day5","Day10")
A <- c (5,7,2,0)
B <- c(15,12,16,30)
df <- data.frame(Day,A,B, stringsAsFactors = FALSE)

df$DayNum <- as.numeric(gsub('Day', '', df$Day))
df <- df[order(df$DayNum), ]

输出如下:

df
    Day A  B DayNum
1  Day1 5 15      1
3  Day5 2 16      5
4 Day10 0 30     10
2 Day20 7 12     20

您可以通过执行以下操作来避免创建新列(试图显示正在发生的事情的完整详细信息):

You can avoid creating a new column by doing the following (was trying to show full detail of what was going on):

df <- df[order(as.numeric(substr(df$Day, 4, nchar(df$Day)))), ]

输出将与上面相同.

这篇关于根据字符列对数据框进行排序,该字符列包含字母,后跟R中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆