mutate() in (d)plyr does not create new column when sourced
Asked Answered
J

2

5

I am using the package dplyr with R (same problem applies to plyr, too). When I call source("dply_problem.R") to the following code

library("dplyr")

df <- data.frame("A" = 1:6,
                 "B" = 7:12)
mutate(df, C = A + B)

the column "C" does not get added to df. However, when I call mutate(df, C = A + B) from the shell, the column "C" does get created. Could you give me a hint why this is happening?

Joni answered 4/4, 2014 at 15:34 Comment(1)
Did you try assigning the output of mutate to "df"?Mammoth
M
23

You haven't assigned the output to anything. Try:

library("dplyr")

df <- data.frame("A" = 1:6,
                 "B" = 7:12)
df <- mutate(df, C = A + B)

df
Mammoth answered 4/4, 2014 at 15:39 Comment(1)
@Joni if this answer suits your needs you may want to consider marking the checkmark next to it to indicate to future searchers that this answer most correctly suited the question.Consent
W
1

This can also be done using pipe operator. dplyr imports this operator from another package (magrittr)

library(dplyr)
df <- data.frame("A" = 1:6,
                 "B" = 7:12)
df1<- df %>% mutate(C = A + B)
Wineshop answered 19/11, 2018 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.