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

重新排序dataframe中的单个列,而不重新排序整个表

  •  0
  • Shinobi_Atobe  · 技术社区  · 8 年前

    我有一个这样的数据框

    set.seed(42069)
    df <- data.frame(matrix(rexp(50), nrow = 10, ncol = 5))
    names(df) <- paste0(rep("variable_", 5), 1:5)
    
    | variable_1| variable_2| variable_3| variable_4| variable_5|
    |----------:|----------:|----------:|----------:|----------:|
    |  0.0975792|  2.2732604|  0.7981710|  0.1009557|  0.5469156|
    |  1.4837063|  4.8105384|  0.3379726|  0.4386950|  0.8297455|
    |  0.4580504|  0.0611627|  0.2248929|  0.5248615|  0.3160315|
    |  0.1399439|  0.0805528|  0.1659186|  2.8510678|  0.5632555|
    |  0.3829142|  0.6337043|  0.3341908|  0.2989038|  0.4339512|
    |  6.5265164|  1.0946979|  1.7983602|  0.0435821|  0.6222236|
    |  0.7618944|  1.4892511|  1.2600329|  0.4313751|  0.5948537|
    |  0.5911888|  0.1326767|  0.7368028|  0.9389244|  0.6276355|
    |  0.6227433|  0.1099597|  1.0445907|  0.1304709|  3.1539861|
    |  0.0617808|  0.3641891|  1.2629195|  0.2675279|  1.5714020|
    

    我想按升序排列第2列和第4列,但保留其他变量不变

    这是我要找的输出:

    | variable_1| variable_2| variable_3| variable_4| variable_5|
    |----------:|----------:|----------:|----------:|----------:|
    |  0.0975792|  0.0611627|  0.7981710|  0.0435821|  0.5469156|
    |  1.4837063|  0.0805528|  0.3379726|  0.1009557|  0.8297455|
    |  0.4580504|  0.1099597|  0.2248929|  0.1304709|  0.3160315|
    |  0.1399439|  0.1326767|  0.1659186|  0.2675279|  0.5632555|
    |  0.3829142|  0.3641891|  0.3341908|  0.2989038|  0.4339512|
    |  6.5265164|  0.6337043|  1.7983602|  0.4313751|  0.6222236|
    |  0.7618944|  1.0946979|  1.2600329|  0.4386950|  0.5948537|
    |  0.5911888|  1.4892511|  0.7368028|  0.5248615|  0.6276355|
    |  0.6227433|  2.2732604|  1.0445907|  0.9389244|  3.1539861|
    |  0.0617808|  4.8105384|  1.2629195|  2.8510678|  1.5714020|
    

    我试过:

    df %>%
      mutate_at(vars(variable_2, variable_4), funs(arrange(.)))
    
    3 回复  |  直到 8 年前
        1
  •  1
  •   Zoe - Save the data dump 张群峰    8 年前

    适应 AndrewGustar's comment ,这有效:

    df %>%
      mutate_at(vars(variable_2, variable_4), funs(sort(., decreasing = F)))
    
        2
  •  0
  •   SatZ    8 年前

    你可以用 cbind

    set.seed(42069)
    df <- data.frame(matrix(rexp(50), nrow = 10, ncol = 5))
    names(df) <- paste0(rep("variable_", 5), 1:5)
    
    df<-data.frame(cbind(df[,c("variable_1","variable_3","variable_5")],variable_2=df[order(df$variable_2),c("variable_2")],variable_4=df[order(df$variable_4),c("variable_4")]))[,paste0(rep("variable_", 5), 1:5)]
    

    一定有更整洁的方法。

        3
  •  0
  •   fidelin    8 年前

    有点像

    df_2 <- apply(df, 2, function(x) x[order(x, decreasing = T)])
    
    推荐文章