Writing this is clunky:
df$a <- df$b + df$c
Is there a way to do (the equivalent of):
with df:
$a <- $b + $c
Writing this is clunky:
df$a <- df$b + df$c
Is there a way to do (the equivalent of):
with df:
$a <- $b + $c
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)