Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use %>% with replacement functions like colnames()<-

Tags:

r

dplyr

magrittr

How can I use the pipe operator to pipe into replacement function like colnames()<- ?

Here's what I'm trying to do:

library(dplyr) averages_df <-     group_by(mtcars, cyl) %>%    summarise(mean(disp), mean(hp)) colnames(averages_df) <- c("cyl", "disp_mean", "hp_mean") averages_df  # Source: local data frame [3 x 3] #  #   cyl disp_mean   hp_mean # 1   4  105.1364  82.63636 # 2   6  183.3143 122.28571 # 3   8  353.1000 209.21429 

But ideally it would be something like:

averages_df <-    group_by(mtcars, cyl) %>%   summarise(mean(disp), mean(hp)) %>%   add_colnames(c("cyl", "disp_mean", "hp_mean")) 

Is there a way to do this without writing a specialty function each time?

The answers here are a start, but not exactly my question: Chaining arithmetic operators in dplyr

like image 439
Alex Coppock Avatar asked Jan 22 '15 23:01

Alex Coppock


People also ask

How do I replace Colnames in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.

How do I get Colnames in R?

To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in. This operation will then return the column you want as a vector.

What is the difference between Colnames () and names ()?

names() creates name attributes where as colnames() simply names the columns.

What does Colnames mean in R?

colnames() function in R Language is used to set the names to columns of a matrix. Syntax: colnames(x) <- value.


1 Answers

You could use colnames<- or setNames (thanks to @David Arenburg)

group_by(mtcars, cyl) %>%   summarise(mean(disp), mean(hp)) %>%   `colnames<-`(c("cyl", "disp_mean", "hp_mean"))   # or   # `names<-`(c("cyl", "disp_mean", "hp_mean"))   # setNames(., c("cyl", "disp_mean", "hp_mean"))   #   cyl disp_mean   hp_mean # 1   4  105.1364  82.63636 # 2   6  183.3143 122.28571 # 3   8  353.1000 209.21429 

Or pick an Alias (set_colnames) from magrittr:

library(magrittr) group_by(mtcars, cyl) %>%   summarise(mean(disp), mean(hp)) %>%   set_colnames(c("cyl", "disp_mean", "hp_mean")) 

dplyr::rename may be more convenient if you are only (re)naming a few out of many columns (it requires writing both the old and the new name; see @Richard Scriven's answer)

like image 105
Henrik Avatar answered Sep 28 '22 07:09

Henrik