我有一个像这样的数据框
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)
第一列是一个字符,因此我使用this solution对此数据帧进行排序,但并未完全正确,因为这只对第一列进行排序并离开第2列和第2列。 3不变。
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
我在这里缺少什么?请提供一些意见。
答案 0 :(得分:2)
您可以尝试使用类似数字日排序的内容:
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
您可以通过执行以下操作来避免创建新列(试图显示正在发生的事情的完整详细信息):
df <- df[order(as.numeric(substr(df$Day, 4, nchar(df$Day)))), ]
输出与上述相同。
答案 1 :(得分:1)
可以使用mixedorder
library(gtools)
来完成此操作
library(gtools)
df[mixedorder(df$Day),]
# Day A B
#1 Day1 5 15
#3 Day5 2 16
#4 Day10 0 30
#2 Day20 7 12
答案 2 :(得分:0)
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)
# add leading zero(s) to digits in values of Day column,
# e.g., "Day5" --> "Day05"
# then return the indices of the sorted vector
indices_to_sort_by <- sort(
sub(
pattern = "([a-z]{1})([1-9]{1}$)",
replacement = "\\10\\2",
x = df$Day
),
index.return = TRUE)$ix
df[indices_to_sort_by, ]
# Day A B
# 1 Day1 5 15
# 3 Day5 2 16
# 4 Day10 0 30
# 2 Day20 7 12