How to add mutated variable to tibble

The sample code is below, as well as the packages I was using when I had my issue. I am trying to mean center a variable (in this example, the variable is called apple). After using mutate, I tried to create a new variable called "apple_cent," which contains the centered values. The new variable appears in the printout in the R console, but when I use View to look at the tibble, the new variable is not there. How can I join "apple_cent" with the rest of the tibble? Many thanks for any assistance with this.

#sandbox
library(tidyverse)
library(knitr)
library(lavaan)
#> Warning: package 'lavaan' was built under R version 3.4.4
#> This is lavaan 0.6-1
#> lavaan is BETA software! Please report any bugs.
library(psych)
#> 
#> Attaching package: 'psych'
#> The following object is masked from 'package:lavaan':
#> 
#>     cor2cov
#> The following objects are masked from 'package:ggplot2':
#> 
#>     %+%, alpha
library(MBESS)
#> 
#> Attaching package: 'MBESS'
#> The following object is masked from 'package:psych':
#> 
#>     cor2cov
#> The following object is masked from 'package:lavaan':
#> 
#>     cor2cov
library(semPlot)
library(haven)
install.packages("reprex")
#> 
#> The downloaded binary packages are in
#>  /var/folders/5f/fjy6f99x2nj4dvp4lz48n5p80000gn/T//Rtmpgsu1AI/downloaded_packages
library(reprex)
#> Warning: package 'reprex' was built under R version 3.4.4

testcase<-tibble(apple = 1:5, bagel = 1, cheese = apple ^ 2 + bagel)
testcase %>%
  mutate(apple_cent=apple-mean(apple))
#> # A tibble: 5 x 4
#>   apple bagel cheese apple_cent
#>   <int> <dbl>  <dbl>      <dbl>
#> 1     1  1.00   2.00      -2.00
#> 2     2  1.00   5.00      -1.00
#> 3     3  1.00  10.0        0   
#> 4     4  1.00  17.0        1.00
#> 5     5  1.00  26.0        2.00
View(testcase)

dplyr doesn't do modifications "in place", it creates a new dataframe instead, you have to manually assign it to the original object.

testcase <- testcase %>%
  mutate(apple_cent=apple-mean(apple))
1 Like

I suggest you call library(magrittr) explicitly and then use the assignment pipe as follows:

testcase %<>%
  mutate(apple_cent=apple-mean(apple))

That worked, thank you.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.