在R中,我使用dplyr,更具体地说arrange()。该arrange功能某种程度上无法按预期工作。
在下面的示例中,首先存储列的名称,然后将该变量作为参数传递给名为“ my_function”的自定义函数。
target_column = 'mean_age'
# below the function
my_function <- function(target_column, number){
df <- read.csv('file.csv', stringsAsFactors=FALSE)
df <- df[, c(1,4,10)]
names(df) <- c('place','state','mean_age')
df1 <- df %>% group_by(state) %>% arrange(target_column)
df1 %>% summarise(rank = nth(target_column, number))
}
Run Code Online (Sandbox Code Playgroud)
当由于输入以下内容而调用“ my_function”时,R返回错误arrange():
“ range_impl(.data,点)中的错误:位置1处的大小(1)不正确,预期为4000”
当将列名直接放入时arrange(),它会接受参数,而不是引用字符串的变量(如上述示例)。
df %>% group_by(state) %>% arrange(mean_age)
Run Code Online (Sandbox Code Playgroud)
我如何以一种更好的方式将列名的参数传递给“ my_function”,这样arrange()才能识别它?