R重命名函数中传递的列 [英] R renaming passed columns in functions
问题描述
我一直在搜索此文件,并找到了此链接有助于重命名函数中传递的列( [,column_name]
代码实际上使 my_function1
工作搜寻了一段时间之后,是否可以使用管道运算符重命名函数中数据框中的列?
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_function2
,但它给了我一个错误:必须重命名所有重命名的参数
或错误:未知变量:col2
。我猜是因为我没有指定 col2
属于什么。
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.
此外,还有一种方法可以将关联的参数传递给函数,例如col1和new_col1,以便您可以将要替换的列名和要替换的列名相关联。
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")
推荐答案
在 @MatthewPlourde对类似问题的回答,我们可以这样做:
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
许多dplyr函数的知识较少名称以 _
结尾的n个变体。使您可以更编程地使用软件包。一种模式是...
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", ...))
这在某些情况下对我有用,其中 val *
只是列名。键入 vignette( nse)
时弹出的文档中包含更复杂的模式和技术,但我不太了解它们。
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.
这篇关于R重命名函数中传递的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!