-1

Here is my example

library('dplyr')
a <- c(0.2,1.3)
df_test <- data.frame(a)
df_test %>% mutate(a =round(a,0))

it produces:

  a
1 0
2 1

, but does not change original dataframe df_test. How do I assign results of mutate to the same dataframe?

zx8754
  • 52,746
  • 12
  • 114
  • 209
user1700890
  • 7,144
  • 18
  • 87
  • 183
  • 4
    `df_test <- df_test %>% mutate(a =round(a,0))`? – Axeman Jan 03 '17 at 15:42
  • 1
    @Axeman, Thank you!!! – user1700890 Jan 03 '17 at 15:43
  • 1
    You should start by reading some R tutorials. There is nothing related to dplyr here really. – David Arenburg Jan 03 '17 at 15:53
  • @DavidArenburg, I read 2 R tutorials, it is just very difficult for me to wrap my head around R. – user1700890 Jan 03 '17 at 15:58
  • 1
    So when you are working with Python or any other language, does any object is being updated by itself without you are using the `=` operator? I know that in pandas you could explicitly specify `inplace=True`, but I don't see why would you assume such thing to be the default behavior of dplyr and even so, why wouldn't you at-least try using the `=` or `<-` operators – David Arenburg Jan 03 '17 at 16:01
  • @DavidArenburg, I agree, but for some reason, I thought that `dplyr` would change assignment operator to `%>%` or `%<%`, which I tried. Lack of understanding of unifying philosophy of R, makes me do weird thinks, I agree, that my questions is stupid, but R is wild to me. – user1700890 Jan 03 '17 at 16:06
  • The `%>%` is just equivalent to `.` in most functional languages such as Python or Scala. Though maybe the difference is that unlike in those languages, anything that comes after it doesn't have to be a method of the previous object- hence it's behavior could be sometimes unpredictable. And it's not R. This is just some relatively new operator that was introduced in some package and went viral for some reason. You could very well survive without using it even once. I for instance, have not a single pipe in any code I ever wrote except in my useless SO answers. – David Arenburg Jan 03 '17 at 16:10
  • @DavidArenburg, Oh I love pipes they make so much sense, I used pipes in MongoDB and pipes are conceptually beautiful. – user1700890 Jan 03 '17 at 16:12
  • Well, apparently you are not the only one – David Arenburg Jan 03 '17 at 16:15

1 Answers1

24

We can use the %<>% compound assignment operator from magrittr to change in place

library(magrittr)
df_test %<>% 
        mutate(a = round(a,0))

If we are using data.table, the assignment (:=) operator does this in place too without copying

library(data.table)
setDT(df_test)[, a := round(a,0)]    
akrun
  • 874,273
  • 37
  • 540
  • 662