How to use magrittr :: inset ()?

I understand that magrittr::inset() should be able to assign a vector to a new column in the data frame (as opposed to extract() ). But I do not understand how the syntax should work.

Let's say I have an example with a toy:

 df = data.frame( id = 1:26, letter = letters) newvalue = rnorm(26) 

I would like to add newvalue as a new column in df in the magrittr chain. I am assuming something like:

 df %>% inset('new_column_name', newvalue) 

But this does not work, apparently because I do not quite understand what the syntax should look like for [<- (for which inset() is an alias).

Beyond the magrittr chain, I could do:

 df['new_column_name'] <- newvalue 

But my question is how to do this in a chain where I have already performed various and different operations.

+6
source share
1 answer

Taking your example against my quick comment:

 library(magrittr) df <- data.frame( id = 1:26, letter = letters) newvalue <- rnorm(26) 

Here is all you need to do:

 df %>% inset("newvalue", value=newvalue) ## id letter newvalue ## 1 1 a -0.44805172 ## 2 2 b -0.36284495 ## 3 3 c 1.56175094 ## 4 4 d 1.48775535 ## 5 5 e -0.29086149 ## 6 6 f 0.46456966 ## 7 7 g 0.01130394 ## 8 8 h 0.57100808 ## 9 9 i -0.87445603 ## 10 10 j 0.81932107 ... 

But you can skip magrittr inset() in general, as this works:

 `[<-`(df, "newvalue", value=newvalue) ## id letter newvalue ## 1 1 a -0.44805172 ## 2 2 b -0.36284495 ## 3 3 c 1.56175094 ## 4 4 d 1.48775535 ## 5 5 e -0.29086149 ## 6 6 f 0.46456966 ## 7 7 g 0.01130394 ## 8 8 h 0.57100808 ## 9 9 i -0.87445603 ... 

So does:

 df %>% `[<-`("newvalue", value=newvalue) 
+6
source

All Articles