【问题标题】:Sort a dataframe by columns with their names passed as vector按列对数据框进行排序,其名称作为向量传递
【发布时间】:2020-04-15 14:39:16
【问题描述】:

我需要按名称中包含非字母字符的列列表对多个数据框进行排序。对于单个数据集,我将使用 this famous solution 以及变量名称中的空白和内容的解决方法:

df_sorted = df[with(df, order(varname, xtfrm(df[,"varname with blanks and\slashes"]) ) ), ]

但对于多个数据集,使用列名向量作为输入的函数更合适:

sort_by_columns = function(col_names){...}
df_sorted = sort_by_columns(col_names = c("varname","varname with blanks and\slashes"))

如何在我的函数中将向量转换为适合order() 的参数?

【问题讨论】:

    标签: r sorting dataframe vector variable-names


    【解决方案1】:

    如果没有针对您的问题的示例数据集,我将使用 iris 数据作为示例。使用 dplyr 和 tidyeval 将是我的方法。

    library(dplyr)    
    library(datasets)
    data(iris)
    
    # I'll rename one of the columns so that it has a space and a slash (slashes will 
    # need to be escaped to appear in column name
    iris <- iris %>%
        rename('sepal \\length' = 'Sepal.Length')
    
    # Data will be sorted in the order listed
    col_names <- c('sepal \\length', 'Sepal.Width')
    
    data_sorted <- iris %>%
        arrange(!!!syms(col_names))
    

    把它变成一个函数:

    sort_by_columns <- function(data, col_names){
      data_sorted <- data %>%
          arrange(!!!syms(col_names))
    
      return(data_sorted)
    }
    

    【讨论】:

    • 令人印象深刻。非常感谢和赞成。很抱歉没有提供示例数据集。
    猜你喜欢
    • 2014-06-02
    • 1970-01-01
    • 2018-06-11
    • 2011-11-12
    • 2018-03-18
    • 1970-01-01
    相关资源
    最近更新 更多