组内标度变量常量

scale variable constant within group

所以我不确定如何表达这个问题,但它很基础。我当然想找到一种优雅的方式将其包含在 dplyr-esque 管道中。

假设我有一个数据框

set.seed(1)
dd <- data.frame(id = rep(c(1,2), c(3,5)),
                 x = rnorm(8), 
                 d = rep(c(0.3, 0.5), c(3,5)))

我想用缩放版本替换 d,即我想要

而不是 0.3 和 0.5
> as.numeric(scale(c(0.3, 0.5)))
[1] -0.7071068  0.7071068

当我在管道中使用scale时唯一的问题是较大的组(id = 2)获得更多的权重,并且获得的值是

> dd %>% 
+   mutate(scale_d = scale(d))
  id          x   d    scale_d
1  1 -0.6264538 0.3 -1.2076147
2  1  0.1836433 0.3 -1.2076147
3  1 -0.8356286 0.3 -1.2076147
4  2  1.5952808 0.5  0.7245688
5  2  0.3295078 0.5  0.7245688
6  2 -0.8204684 0.5  0.7245688
7  2  0.4874291 0.5  0.7245688
8  2  0.7383247 0.5  0.7245688

我觉得这应该是一个很简单的问题,所以也许有一个简单的解决方案?

你可以暂时nest x:

library(tidyverse)

dd %>% 
    nest(x) %>% 
    mutate(scale_d = scale(d)) %>% 
    unnest()

## # A tibble: 8 × 4
##      id     d    scale_d          x
##   <dbl> <dbl>      <dbl>      <dbl>
## 1     1   0.3 -0.7071068 -0.6264538
## 2     1   0.3 -0.7071068  0.1836433
## 3     1   0.3 -0.7071068 -0.8356286
## 4     2   0.5  0.7071068  1.5952808
## 5     2   0.5  0.7071068  0.3295078
## 6     2   0.5  0.7071068 -0.8204684
## 7     2   0.5  0.7071068  0.4874291
## 8     2   0.5  0.7071068  0.7383247