Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr mutate colnames in pipe function

Tags:

r

dplyr

I have the following code:

library(dplyr)

df <- data %>%
  left_join(., panel_info, by = "PANID") %>%
  left_join(., prod_0106, by = "UPC") %>%
  left_join(., prod_0106sz, by = "UPC") %>%
  left_join(., trips, by = "PANID") %>%
  mutate(colnames(.) = gsub(" ", "", colnames(.)))

Everything works except the last line. The df data frame has not been created previously. So using the pipe function I am trying to join all the data together and finally remove all the blank spaces in the column names of the joined together data.

However, the following error occurs;

Error in mutate_impl(.data, dots) : 
  Column `gsub(" ", "", colnames(.))` must be length 20056 (the number of rows) or one, not 106

Which I assume is due to the (.) in the mutate() part of the code. Just want to see where I am going wrong here.

like image 244
user113156 Avatar asked Jan 28 '26 13:01

user113156


1 Answers

You can also set colnames in a dplyr pipe by piping into `colnames<-()` which is the generic form of the function called when you do colnames(df) <- c('a', 'b', 'c'):

iris %>%
    `colnames<-`(gsub('Length', 'LENGTH', names(.))) %>%
    head

  Sepal.LENGTH Sepal.Width Petal.LENGTH Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
like image 131
divibisan Avatar answered Jan 31 '26 04:01

divibisan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!