我正面临一个思维和编程问题。看到下面的问题,我不知道什么是正确的方法(使用DPLYR的group_by,但没有结果)。在此先感谢您尝试帮助我!
我有一个这样的数据集:
Numbers Area Cluster
1 A 1
0.8 A 1
0.78 A 1
0.7 B 1
0.4 A 2
0 C 1
我要计算两个新列:
结果应该是这样的:
Numbers Area Cluster Example_1 Example_2
1 A 1 60% #5x cluster 1, and 3x Area A) 1
0.8 A 1 60% 0.8
0.78 A 1 60% 0.78
0.7 B 1 20% 0.7
0.4 A 2 100% 1
0 C 1 20% 0
答案 0 :(得分:2)
由于要保留所有行,因此可以如下计算相对频率:
library(tidyverse)
df <- data.frame(numbers = c(1, .8, .78, .7, .4, 0),
area = c("A", "A", "A", "B", "A", "C"),
cluster = c(1, 1, 1, 1, 2, 1))
df %>%
group_by(cluster) %>%
mutate(example_1 = n()) %>%
group_by(area, cluster) %>%
mutate(example_1 = n() / example_1)
# A tibble: 6 x 4
# Groups: area, cluster [4]
numbers area cluster example_1
<dbl> <fct> <dbl> <dbl>
1 1 A 1 0.6
2 0.8 A 1 0.6
3 0.78 A 1 0.6
4 0.7 B 1 0.2
5 0.4 A 2 1
6 0 C 1 0.2
答案 1 :(得分:1)
您也可以使用data.table
:
library(magrittr)
library(data.table)
df <- data.table(Numbers = c(1, .8, .78, .7, .4, 0),
Area = c(rep("A", 3), "B", "A", "C"),
Cluster = c(rep(1, 4), 2, 1))
df[, N := .N, by = c("Cluster")] %>%
.[, Example_1 := .N/N, by = c("Cluster", "Area")] %>%
.[, `:=`(N = NULL, Example_2 = Numbers)]
输出:
> df
Numbers Area Cluster Example_1 Example_2
1: 1.00 A 1 0.6 1.00
2: 0.80 A 1 0.6 0.80
3: 0.78 A 1 0.6 0.78
4: 0.70 B 1 0.2 0.70
5: 0.40 A 2 1.0 0.40
6: 0.00 C 1 0.2 0.00