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
  • 11,755
  • 5
  • 49
  • 77

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
  • 377,200
  • 20
  • 156
  • 213