Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use magrittr::inset()?

Tags:

r

magrittr

I understand that magrittr::inset() should be able to assign a vector to a new column in a dataframe (as a sort of opposite of extract()). But I don't understand how the syntax should work.

Say I've got, as a toy example:

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

I'd like to add newvalue as a new column to df within a magrittr chain. I'm assuming it's something like:

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

But that doesn't work, presumably because I don't quite understand what the syntax for [<- (for which inset() is an alias) should look like.

Outside of a magrittr chain, I could do:

df['new_column_name']  <- newvalue

But my question is how to do it within a chain, where I've already done various and asundry operations.

like image 924
crazybilly Avatar asked Aug 20 '15 16:08

crazybilly


1 Answers

Taking your example vs my quick comment:

library(magrittr)

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

newvalue <- rnorm(26)

Here's 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's inset() altogether since 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)
like image 103
hrbrmstr Avatar answered Nov 13 '22 16:11

hrbrmstr