我正在按月尋找顏色頻率。我想用每個月的每種顏色的百分比制作一個折線圖。這是我的資料:
ID color1 color2 color3 date
55 red blue NA 2020-03-15
67 yellow NA NA 2020-05-02
83 blue yellow NA 2020-05-17
78 red yellow blue 2020-05-15
43 green NA NA 2021-01-27
29 yellow green NA 2021-01-03
我需要這樣的東西來繪制圖表。我需要將當月的文章數作為分母。因此,如果ID有多種顏色(例如,所有IDs的03/2020都是藍色和紅色),總百分比可能高于100。
Month n freq_blue freq_red freq_yellow freq_green %_blue %_red _yellow %_green
03-2020 1 1 1 0 0 100 100 0 0
04-2020 0 0 0 0 0 0 0 0 0
05-2020 3 2 1 3 0 66.7 33.3 100 0
06-2020 0 0 0 0 0 0 0 0 0
07-2020 0 0 0 0 0 0 0 0 0
08-2020 0 0 0 0 0 0 0 0 0
09-2020 0 0 0 0 0 0 0 0 0
10-2020 0 0 0 0 0 0 0 0 0
11-2020 0 0 0 0 0 0 0 0 0
12-2020 0 0 0 0 0 0 0 0 0
01-2021 2 0 0 1 2 0 0 50 100
uj5u.com熱心網友回復:
正如建議的那樣,如果您可以使用代碼而不是在下面的評論中編輯原始帖子/問題,將會很有幫助。
根據您所擁有的(以及您之前的問題),這可能會有所幫助。
考慮創建一個month_total可用于百分比計算的新列- 您似乎想知道給定月份的 ID 數量(不清楚一種顏色是否可以連續出現多次)。
在確定頻率和百分比并用于complete填充缺失的月份和顏色后,您還可以使用fill包括每月總計。
library(tidyverse)
library(lubridate)
df$date <- as.Date(df$date)
df %>%
mutate(month = month(date), year = year(date)) %>%
pivot_longer(cols = starts_with("color")) %>%
filter(!is.na(value)) %>%
group_by(month, year) %>%
mutate(month_total = n_distinct(ID)) %>%
group_by(value, month_total, .add = T) %>%
summarise(freq = n(), percent = freq/month_total[1] * 100) %>%
ungroup() %>%
complete(year, month = 1:12, value = c("blue", "red", "yellow", "green"), fill = list(freq = 0, percent = 0)) %>%
group_by(year, month) %>%
fill(month_total, .direction = "updown") %>%
pivot_wider(id_cols = c(month, year, month_total), names_from = value, values_from = c(freq, percent)) %>%
replace_na(list(month_total = 0))
輸出
month year month_total freq_blue freq_green freq_red freq_yellow percent_blue percent_green percent_red percent_yellow
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 2020 0 0 0 0 0 0 0 0 0
2 2 2020 0 0 0 0 0 0 0 0 0
3 3 2020 1 1 0 1 0 100 0 100 0
4 4 2020 0 0 0 0 0 0 0 0 0
5 5 2020 3 2 0 1 3 66.7 0 33.3 100
6 6 2020 0 0 0 0 0 0 0 0 0
7 7 2020 0 0 0 0 0 0 0 0 0
8 8 2020 0 0 0 0 0 0 0 0 0
9 9 2020 0 0 0 0 0 0 0 0 0
10 10 2020 0 0 0 0 0 0 0 0 0
# … with 14 more rows
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383590.html
