dplyr's rename functions require the new column name to be passed in as unquoted variable names. However I have a function where the column name is constructed by pasting a string onto an argument passed in and so is a character string.
For example say I had this function
myFunc <- function(df, col){
new <- paste0(col, '_1')
out <- dplyr::rename(df, new = old)
return(out)
}
If I run this
df <- data.frame(a = 1:3, old = 4:6)
myFunc(df, 'x')
I get
a new
1 1 4
2 2 5
3 3 6
Whereas I want the 'new' column to be the name of the string I constructed ('x_1'), i.e.
a x_1
1 1 4
2 2 5
3 3 6
Is there anyway of doing this?
dplyr 0.3
: "You can now program withdplyr
– every function that uses non-standard evaluation (NSE) also has a standard evaluation (SE) twin that ends in_
[...] The SE version of each function has similar arguments, but they must be explicitly “quoted”." Thus, check ifrename_
might be useful here. - Henrikcolnames(df)[colnames(df) %in% "old"] <- paste0("x","_")
(in a function if that is necessary) as it is able to replace a vector of names easily. - akrundf
<%>`new <- c("a.new", "b.new")
%>%names(.) <- rename_(new)
- mtelesha