Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a column to a variable name "in a tidyverse way"

Tags:

r

dplyr

tidyverse

I've created a simple data frame (dput below):

    date      ticker     value
------------------------------
  2016-06-30  A2M.ASX   0.0686
  2016-07-29  A2M.ASX  -0.0134
  2016-08-31  A2M.ASX  -0.0650
  2016-09-30  A2M.ASX   0.0145
  2016-10-31  A2M.ASX   0.3600
  2016-11-30  A2M.ASX  -0.1429

I want to change the value column's name to whatever is in my metric variable name, and I want to do it in a dplyr way.

My sample data:

df = structure(list(date = c("2016-06-30", "2016-07-29", "2016-08-31", "2016-09-30", "2016-10-31", "2016-11-30"), ticker = c("A2M.ASX", "A2M.ASX", "A2M.ASX", "A2M.ASX", "A2M.ASX", "A2M.ASX"), value = c(0.0686, -0.0134, -0.065, 0.0145, 0.36, -0.1429)), .Names = c("date", "ticker", "value"), row.names = c(NA, 6L), class = "data.frame")
metric = "next_return"

I know how to do it in one line:

colnames(df)[3] = metric

But I want do it in a tidyverse way so I can use it in a pipe. I've been tinkering with replace_ but I only manage to get errors:

> dplyr::rename_(df, "ticker" = metric)
Error: `next_ret_1M` contains unknown variables
like image 344
lebelinoz Avatar asked Aug 02 '17 23:08

lebelinoz


People also ask

How do I rename a column in a Python dplyr?

For example, you can pass the variables you want to rename as strings. In your example, the paste0 function can be used to append on the appropriate suffix to each column. For dplyr_1.0.0, use rename_with (). The function argument comes before the column argument. You can use the tidy-select function all_of () (or others) to choose columns.

How can I rename a column in a database?

Ideally we should be able to provide a character/string vector of interest as new column names. A better solution would be to have a dictionary (like Pandas rename () function in Python) or a lookup table containing current column name and the new column names.

How to replace a pattern in a MySQL column name?

If we wanted to replace the common string in the names to something else, we can use rename_with () function in combination with substitute function like gsub to replace a pattern. In this example, we have changed “var” in column names to “variable”.

How do I rename a column in azure synapse analytics?

Note: In Azure Synapse Analytics, sp_rename is in Preview for dedicated SQL pools and can only be used to rename a COLUMN in a user object. The following example renames the MedallionID column in the tripoutput table to MID. EXEC sp_rename 'dbo.tripoutput.MedallionID', 'MID', 'COLUMN';


1 Answers

With the newest dplyr (>0.7.0) you would use

rename(df, !!metric:=value)

The syntax is "new_name=old_name" and you need to use := with !! to put a variable on the left side of a parameter name.

like image 169
MrFlick Avatar answered Oct 17 '22 16:10

MrFlick