如何从R中的其他组中减去一组的值

时间:2021-04-17 14:38:31

标签: r

我试图从另一组中减去一组的值。我希望使用 tidyverse

structure(list(A = c(1, 1, 1, 2, 2, 2, 3, 3, 3), group = c("a", 
"b", "c", "a", "b", "c", "a", "b", "c"), value = c(10, 11, 12, 
11, 40, 23, 71, 72, 91)), class = "data.frame", row.names = c(NA, 
-9L))

这是我的数据,我想从 B 和 C 中减去 A 组的所有值,并将差值存储在一个变量中。

2 个答案:

答案 0 :(得分:2)

我只使用了 data.table 而不是 data.frame 因为我更熟悉。

library(data.table)

data <- setDT(structure(list(A = c(1, 1, 1, 2, 2, 2, 3, 3, 3), group = c("a", 
 "b", "c", "a", "b", "c", "a", "b", "c"), value = c(10, 11, 12, 
  11, 40, 23, 71, 72, 91)), class = "data.frame", row.names = c(NA,-9L)))

for (i in 1:length(unique(data$A))){
  data[A == i, substraction := data[A == i, 'value'] - data[A == i & group == 'a', value]]
}

enter image description here

答案 1 :(得分:2)

baseR 解决方案

df$new <- df$value - ave(df$value, df$A, FUN = function(x) mean(x[df$group == 'a'], na.rm = T) )

> df
  A group value new
1 1     a    10   0
2 1     b    11   1
3 1     c    12   2
4 2     a    11   0
5 2     b    40  29
6 2     c    23  12
7 3     a    71   0
8 3     b    72   1
9 3     c    91  20

dplyr 方法(假设每组不超过一个 a 值,否则 R 会混淆要减去哪个值并导致错误)

df %>% group_by(A) %>% mutate(new = ifelse(group != 'a', value - value[group == 'a'], value) )

# A tibble: 9 x 4
# Groups:   A [3]
      A group value   new
  <dbl> <chr> <dbl> <dbl>
1     1 a        10    10
2     1 b        11     1
3     1 c        12     2
4     2 a        11    11
5     2 b        40    29
6     2 c        23    12
7     3 a        71    71
8     3 b        72     1
9     3 c        91    20

或者如果您想更改所有值

df %>% group_by(A) %>% mutate(new = value - value[group == 'a'] )

# A tibble: 9 x 4
# Groups:   A [3]
      A group value   new
  <dbl> <chr> <dbl> <dbl>
1     1 a        10     0
2     1 b        11     1
3     1 c        12     2
4     2 a        11     0
5     2 b        40    29
6     2 c        23    12
7     3 a        71     0
8     3 b        72     1
9     3 c        91    20
相关问题