R renaming passed columns in functions

◇◆丶佛笑我妖孽 提交于 2020-06-16 04:35:16

问题


I have been searching this and have found this link to be helpful with renaming passed columns from a function (the [,column_name] code actually made my_function1 work after I had been searching for a while. Is there a way to use the pipe operator to rename columns in a dataframe within a function?

My attempt is shown in my_function2 but it gives me an Error: All arguments to rename must be named or Error: Unknown variables: col2. I am guessing because I have not specified what col2 belongs to.

Also, is there a way to pass associated arguments into the function, like col1 and new_col1 so that you can associated the column name to be replaced and the column name that is replacing it. Thanks in advance!

library(dplyr)

my_df = data.frame(a = c(1,2,3), b = c(4,5,6), c = c(7,8,9))

my_function1 = function(input_df, col1, new_col1) {
  df_new = input_df
  df_new[,new_col1] = df_new[,col1]
  return(df_new)
}
temp1 = my_function1(my_df, "a", "new_a")

my_function2 = function(input_df, col2, new_col2) {
  df_new = input_df %>%
    rename(new_col2 = col2)
  return(df_new)
}

temp2 = my_function2(my_df, "b", "new_b")

回答1:


Following @MatthewPlourde's answer to a similar question, we can do:

my_function3 = function(input_df, cols, new_cols) { 
  rename_(input_df, .dots = setNames(cols, new_cols)) 
}

# example
my_function3(my_df, "b", "new_b")
#   a new_b c
# 1 1     4 7
# 2 2     5 8
# 3 3     6 9

Many dplyr functions have less-known variants with names ending in _. that allow you to work with the package more programmatically. One pattern is...

DF %>% dplyr_fun(arg1 = val1, arg2 = val2, ...)
# becomes
DF %>% dplyr_fun_(.dots = list(arg1 = "val1", arg2 = "val2", ...))

This has worked for me in a few cases, where the val* are just column names. There are more complicated patterns and techniques, covered in the document that pops up when you type vignette("nse"), but I do not know them well.




回答2:


rename_ (alongside other dyplyr verbs suffixed with an underscore) has been depreciated. Instead, try:

my_function3 = function(input_df, cols, new_cols) { 
  input_df %>%
    rename({{ new_cols }} := {{ cols }})) 
}

See this vignette for more information about embracing arguments with double braces and programming with dplyr.



来源:https://stackoverflow.com/questions/35023375/r-renaming-passed-columns-in-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!