按字母和数字列排序数据框

时间:2018-04-14 14:30:11

标签: 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都是相同的,除了它们的值略有不同。

1 个答案:

答案 0 :(得分:4)

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 给出了可用于对行进行排序的有序索引

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

目前尚不清楚OP的绘图方式。

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))

https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin

数据

babel-register