英文:
Subtract one group of values from all groups using group_by
问题
你可以使用以下代码来使用 group_by
在 tibble 中从所有值中减去类别 "A" 的值。以下是一个示例和预期结果:
library(dplyr)
d <- tibble(categories = c(rep("A", 3), rep("B", 3), rep("C", 3)),
values = 1:9)
d <- d %>%
group_by(categories) %>%
mutate(values = values - first(values[categories == "A"]))
# 预期结果
d <- tibble(categories = c(rep("A", 3), rep("B", 3), rep("C", 3)),
values = c(0, 0, 0, 3, 3, 3, 6, 6, 6))
这段代码会将类别 "A" 的值从所有值中减去,得到预期的结果。
英文:
How can I subtract one group of values from all values using group_by
in tibble.
Below is an example with expected results. I wish to subtract values of category "A" from all values
d <- tibble(categories = c(rep("A", 3), rep("B", 3), rep("C", 3)),
values = 1:9)
# expected outcome
d <- tibble(categories = c(rep("A", 3), rep("B", 3), rep("C", 3)),
values = c(0, 0, 0, 3, 3, 3, 6, 6, 6))
</details>
# 答案1
**得分**: 2
如果类别大小相同长度,我们可以执行以下操作:
```R
library(dplyr)
d %>%
mutate(values = values - d$values[d$categories == "A"])
- 输出
# A tibble: 9 × 2
categories values
<chr> <int>
1 A 0
2 A 0
3 A 0
4 B 3
5 B 3
6 B 3
7 C 6
8 C 6
9 C 6
英文:
If the categories size are the same length, we could do
library(dplyr)
d %>%
mutate(values = values - d$values[d$categories == "A"])
-output
# A tibble: 9 × 2
categories values
<chr> <int>
1 A 0
2 A 0
3 A 0
4 B 3
5 B 3
6 B 3
7 C 6
8 C 6
9 C 6
答案2
得分: 0
你可以这样做:
library(tidyverse)
d %>%
group_by(categories) %>%
mutate(id = row_number()) %>%
ungroup() %>%
pivot_wider(names_from = 'categories',
values_from = 'values') %>%
mutate(across(-id, ~ . - A)) %>%
pivot_longer(cols = -id,
names_to = 'categories',
values_to = 'values',
cols_vary = 'slowest') %>%
select(-id)
或者,你也可以尝试以下方法:
d %>%
group_by(categories) %>%
mutate(id = row_number()) %>%
ungroup() %>%
mutate(values = values - values[categories == 'A' & id == id]) %>%
select(-id)
A tibble: 9 x 2
categories values
1 A 0
2 A 0
3 A 0
4 B 3
5 B 3
6 B 3
7 C 6
8 C 6
9 C 6
<details>
<summary>英文:</summary>
You can do:
library(tidyverse)
d %>%
group_by(categories) %>%
mutate(id = row_number()) %>%
ungroup() %>%
pivot_wider(names_from = 'categories',
values_from = 'values') %>%
mutate(across(-id, ~ . - A)) %>%
pivot_longer(cols = -id,
names_to = 'categories',
values_to = 'values',
cols_vary = 'slowest') %>%
select(-id)
Alternatively:
d %>%
group_by(categories) %>%
mutate(id = row_number()) %>%
ungroup() %>%
mutate(values = values - values[categories == 'A' & id == id]) %>%
select(-id)
# A tibble: 9 x 2
categories values
<chr> <int>
1 A 0
2 A 0
3 A 0
4 B 3
5 B 3
6 B 3
7 C 6
8 C 6
9 C 6
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论