![](/img/trans.png)
[英]R: Calculate percentage of observations in a column that are below a certain value for panel data
[英]R - Count observations (strings) in a column and calculate as a percentage of overall observations
嗨,有一些看起來像這樣的數據:
ID Item Class Value Date
1 Eggs A 5 07/07/21
2 Eggs A 4.5 07/07/21
3 Cereal C 2 07/07/21
4 Eggs B 3.5 07/07/21
5 Bread B 2.5 07/07/21
6 Juice A 3 07/07/21
7 Juice C 1.5 07/07/21
8 Eggs C 2 07/07/21
9 Bread A 3 07/07/21
10 Juice A 3 07/07/21
這只是一個示例,實際數據大約有 8k 行(並且有 300 多個數據幀)。 我想創建一個新的 df
Item
欄(例如有10個項目的列,其中四個是Eggs
,從而百分比Eggs
是40)Value
的每一個Item
組理想情況下,最終數據將如下所示:
Item Percentage Average_Value Date
Eggs 40 3.75 07/07/21
Cereal 10 2 07/07/21
Bread 20 2.75 07/07/21
Juice 30 2.5 07/07/21
需要注意的幾件事 - 我想對 300 多個不同的 csv(存儲我的數據的位置)執行此操作,並使用此新信息創建一個 df。 每個 csv 指的是一個不同的日期,所以最終的 df 看起來像上面那樣,只有另外四行,但具有不同的值和不同的日期。 我知道我需要為此使用 for 循環,也許我應該稍后弄清楚那部分,但認為現在值得一提。 最后,在某些時候,我可能還想計算Class
的平均值。 我最好為此制作一個單獨的 df ,因為我看不出我還能怎么做?
您可以merge
table
的proportions
結果與Value ~ Item
的mean
的結果形式aggregate
merge
。 如果Date
也需要在那里,可以使用cbind
或data.frame
添加。
merge(aggregate(cbind(Average_Value = Value) ~ Item, x, mean)
, proportions(table(x$Item))*100
, by.y=1, by.x="Item")[c(1,3,2)]
# Item Freq Average_Value
#1 Bread 20 2.75
#2 Cereal 10 2.00
#3 Eggs 40 3.75
#4 Juice 30 2.50
或者只使用aggregate
:
aggregate(Value ~ Item, x, function(y) c(Freq=length(y)/nrow(x)*100, Average=mean(y)))
# Item Value.Freq Value.Average
#1 Bread 20.00 2.75
#2 Cereal 10.00 2.00
#3 Eggs 40.00 3.75
#4 Juice 30.00 2.50
這是否有效:
library(dplyr)
df %>% group_by(Item) %>% summarise(Percentage = n()/nrow(df)*100, Average_Value = mean(Value))
# A tibble: 4 x 3
Item Percentage Average_Value
<chr> <dbl> <dbl>
1 Bread 20 2.75
2 Cereal 10 2
3 Eggs 40 3.75
4 Juice 30 2.5
在tidyverse
執行這些步驟
temp
date
否則您必須稍微調整代碼map
和imap_dfr
如下所述,您可以為每個文件只執行一次相同的代碼,因此您將擁有一個數據幀setwd('my/path/here')
temp <- list.files(pattern = '*.csv')
library(tidyverse)
map(temp, read.csv) %>% setNames(gsub('.csv', '', temp)) %>%
imap_dfr(~ .x %>% group_by(item) %>%
summarise(Percentage = n()/nrow(df)*100,
Average_Value = mean(Value), .groups = 'drop') %>%
mutate(Date = .y))
如果您所有的 csvs 都包含日期列,請執行此操作
map_dfr(temp, ~read.csv(.x) %>% group_by(item, date) %>%
summarise(Percentage = n()/nrow(df)*100,
Average_Value = mean(Value), .groups = 'drop'))
使用list.files
列出您要使用的所有文件。 使用map_df
它們組合在一個文件中,並為每個Date
計算Item
存在的百分比及其平均值。
library(tidyverse)
filenames <- list.files(pattern = '\\.csv$')
map_df(filenames, read_csv) %>%
group_by(Date, Item) %>%
summarise(Percentage = n(),
Average_Value = mean(Value)) %>%
mutate(Percentage = prop.table(Percentage) * 100) %>%
ungroup -> result
result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.