6

Writing this is clunky:

df$a <- df$b + df$c

Is there a way to do (the equivalent of):

with df:
    $a <- $b + $c
Reinderien
  • 8,154
  • 3
  • 41
  • 70

1 Answers1

7

We can use with command

df$a <- with(df, b + c)

Another option is using attach, which however is not recommended

attach(df)
df$a <- b + c

Another options with data.table and dplyr as suggested by @SymbolixAU

library(data.table)
setDT(df)[, a := b + c]

If you prefer dplyr chains.

library(data.table)
library(dplyr)

df %>%
  mutate(a:= b + c)

There is also forward pipe operator (%<>%) in magrittr package which doesn't require you to assign the object again to the variable.

library(magrittr)
df %<>%
  mutate(a = b + c)

Another one similar to with is using transform (suggested by @Maurits Evers)

df <- transform(df, a = b + c)
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178