簡體   English   中英

根據其他列計算列中的比率

[英]Calculate Ratios in columns, based on other columns

我正面臨思維和編程問題。 看到下面的問題,我不知道什么是正確的方法(使用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 

我想計算兩個新列:

  1. 顯示在特定群集中發生的區域百分比(Column_Example_1)
  2. 每個群集,列號的新索引(范圍為1-0)(Column_example_2)。 新的比率應基於Numbers #note列:在示例中,它只是一個示例,它也可以以其他方式執行,但我們要確保Numbers列處於領先地位)

結果應該是這樣的:

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

由於要保留所有行,因此可以按以下方式計算相對頻率:

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

您也可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM