r - 按字母和数字列对数据框进行排序

标签 r sorting dataframe rows

我一直在尝试使用下面列出的多种不同方法按第一列或第一天对我的数据框进行排序,但无济于事。我怀疑这可能是因为它试图按第一个数字排序,但我不确定我将如何更改它以使其正确排序行。数据集如下:

df1
    [day][sample1][sample2]
[1,]day0    22       11
[2,]day11   23       15
[3,]day15   25       14
[4,]day2    21       13
[5,]day8    20       17
...

我希望按天订购整行。我尝试了以下方法

df[sort(as.character(df$day)),]
df[order(as.character(df$day)),]
mixedorder(as.character(df$day))   (gtools package)

mixedorder 仅输出数字索引。

当前代码:

df_0$day =  metadata_df[,3]
df_0 <- df_0[,c(8,1:7)]
df1 <- aggregate(df_0[,2:ncol(df_0)], df_0[1], mean)
df1 <- df1[mixedorder(as.character(df1$day)),]
df1$day <- factor(df1$day, levels = unique(df1$day))
rownames(df1) <- 1:nrow(df1)
##Plotting expression levels
Plot1 <- ggplot() +
  geom_line(data=df1, aes(x=day, y=sample1, group=1, color="blue"))+
  geom_line(data=df2, aes(x=day, y=sample1, group=2, color="red"))

请注意,我对 df2 进行了与对 df1 相同的转换。 df1 和 df2 都是一样的,只是它们的值略有不同。

最佳答案

mixedorder 给出了可用于对行进行排序的有序索引

df1 <- df[mixedorder(as.character(df$day)),]
df1
#     day sample1 sample2
#1  day0      22      11
#4  day2      21      13
#5  day8      20      17
#2 day11      23      15
#3 day15      25      14

目前尚不清楚 OP 是如何策划的。

library(tidyverse)
df1 %>%
    mutate(day = factor(day, levels = unique(day))) %>% 
    gather(key, val, -day) %>%
    ggplot(., aes(x = day, y = val, color = key)) + 
          geom_point() 

enter image description here

数据

df <- structure(list(day = structure(1:5, .Label = c("day0", "day11", 
"day15", "day2", "day8"), class = "factor"), sample1 = c(22L, 
23L, 25L, 21L, 20L), sample2 = c(11L, 15L, 14L, 13L, 17L)), .Names = c("day", 
 "sample1", "sample2"), class = "data.frame", row.names = c(NA, 
-5L))

关于r - 按字母和数字列对数据框进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49832525/

相关文章:

R 无故复制

bash - 按字符数和字母顺序对列表进行排序

ios - 对 JSON 日期进行排序

python - 基于公共(public)列合并多个数据框

python - 删除任何列子集中具有空值的行( Pandas )

r - 计算一年中的周数(0-53)

r - 无法使用 sf() 和 rnaturalearth() 在 R 中提取湖泊几何数据

python - 按层次算法排序

python - 使用 sklearn 缩放的 pandas 数据框列

r - 计算 cummean() 和 cumsd(),同时忽略 NA 值并填充 NA