代码之家  ›  专栏  ›  技术社区  ›  user1381852

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

  •  3
  • user1381852  · 技术社区  · 7 年前

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

    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 回复  |  直到 7 年前
        1
  •  4
  •   Community CDub    5 年前

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