按列对数据帧进行排序,并将其名称作为向量传递
Sort a dataframe by columns with their names passed as vector
我需要按名称中包含 非字母字符 的列列表对多个数据帧进行排序。对于单个数据集,我将使用 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()
的参数?
没有针对您的问题的示例数据集,我将使用鸢尾花数据作为示例。使用 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)
}
我需要按名称中包含 非字母字符 的列列表对多个数据帧进行排序。对于单个数据集,我将使用 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()
的参数?
没有针对您的问题的示例数据集,我将使用鸢尾花数据作为示例。使用 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)
}