1
votes

I'm trying to re-scale a vector within a grouping variable. So for mtcars I would be trying scale the weight variable, but only within the grouping variable of cylinders.

First try:

mtcars2 <- mtcars %>%
group_by(cyl) %>%
  nest()%>%
  mutate(wt.scaled = purrr::map_dbl(wt, scale)) %>%
  unnest()

ERROR: "wt" not found

2nd try:

mtcars2 <- mtcars %>%
  split(.$cyl) %>%
  purrr::map_dbl(wt, scale)

Error in UseMethod("mutate_") : no applicable method for 'mutate_' applied to an object of class "list"

I don't seem to know how to refer to the wt vector in the nested data.frame. Sorry if this is answered elsewhere. I spent quite a bit of time searching for the answer, but couldn't make the solutions work.

1

1 Answers

0
votes

You can pass data in map and scale wt column of each data.

library(tidyverse)

mtcars %>%
  group_by(cyl) %>%
  nest() %>%
  mutate(wt.scaled = map(data, ~as.numeric(scale(.x$wt)))) %>%
  unnest(c(wt.scaled, data))

#     cyl   mpg  disp    hp  drat    wt  qsec    vs    am  gear  carb wt.scaled
#   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>     <dbl>
# 1     6  21    160    110  3.9   2.62  16.5     0     1     4     4   -1.40  
# 2     6  21    160    110  3.9   2.88  17.0     0     1     4     4   -0.680 
# 3     6  21.4  258    110  3.08  3.22  19.4     1     0     3     1    0.275 
# 4     6  18.1  225    105  2.76  3.46  20.2     1     0     3     1    0.962 
# 5     6  19.2  168.   123  3.92  3.44  18.3     1     0     4     4    0.906 
# 6     6  17.8  168.   123  3.92  3.44  18.9     1     0     4     4    0.906 
# 7     6  19.7  145    175  3.62  2.77  15.5     0     1     5     6   -0.974 
# 8     4  22.8  108     93  3.85  2.32  18.6     1     1     4     1    0.0602
# 9     4  24.4  147.    62  3.69  3.19  20       1     0     4     2    1.59  
#10     4  22.8  141.    95  3.92  3.15  22.9     1     0     4     2    1.52  
# … with 22 more rows

This is same as scaling wt by group :

mtcars %>%
  group_by(cyl) %>%
  mutate(wt.scaled = as.numeric(scale(wt)))