[英]How to subset data frame by date and perform multiple operations in R?
我每天都會收到 CSV 報告,每個報告都有相同數量的變量,但時間不同。 我想根據日期運行一些簡單的分析並保存結果。 我認為for
循環可以完成這項工作,但我只知道基礎知識。 理想情況下,我只需要每月運行一次腳本並獲得結果。 任何指導或建議表示贊賞。
假設我在一個文件夾中有兩個 CSV 報告:
#File 1 - 20200624.csv
Date Market Salesman Product Quantity Price Cost
6/24/2020 A MF Apple 20 1 0.5
6/24/2020 A RP Apple 15 1 0.5
6/24/2020 A RP Banana 20 2 0.5
6/24/2020 A FR Orange 20 3 0.5
6/24/2020 B MF Apple 20 1 0.5
6/24/2020 B RP Banana 20 2 0.5
#File 2 - 20200625.csv
Date Market Salesman Product Quantity Price Cost
6/25/2020 A MF Apple 10 1 0.6
6/25/2020 A MF Banana 15 1 0.6
6/25/2020 A RP Banana 10 2 0.6
6/25/2020 A FR Orange 15 3 0.6
6/25/2020 B MF Apple 20 1 0.6
6/25/2020 B RP Banana 20 2 0.6
我使用以下代碼將所有文件導入 R :
library(readr)
library(dplyr)
#Import files
files <- list.files(path = "~/JuneReports",
pattern = "*.csv", full.names = T)
tbl <- sapply(files, read_csv, simplify=FALSE) %>%
bind_rows(.id = "id")
#Remove the "id" column
tbl2 <- tbl[,-1]
#Subset the data frame to get only Mark A, as Market B is irrelavant.
tbl3 <- subset(tbl2, Market == "A")
head(tbl3)
# A tibble: 6 x 7
Date Market Salesman Product Quantity Price Cost
<chr> <chr> <chr> <chr> <dbl> <dbl> <dbl>
1 6/24/2020 A MF Apple 20 1 0.5
2 6/24/2020 A RP Apple 15 1 0.5
3 6/24/2020 A RP Banana 20 2 0.5
4 6/24/2020 A FR Orange 20 3 0.5
5 6/25/2020 A MF Apple 10 1 0.6
6 6/25/2020 A MF Banana 15 1 0.6
以下是我想要得到的結果:
Date Market Revenue Total Cost Apples Sold Bananas Sold Oranges Sold
6/24/2020 A 135 37.5 35 20 20
6/25/2020 A 90 30 15 25 15
#Revenue = sumproduct(Quantity, Price)
#Total Cost = sumproduct(Quantity, Cost)
#Apples/Bananas/Oranges Sold = sum(Product == "Apple/Banana/Orange")
我們按“日期”、“市場”分組,計算“數量”與“價格”和“成本”的產品總和,將其與“產品”一起添加到.add
group_by
,得到“數量”的sum
並使用pivot_wider
重塑為“寬”格式
library(dplyr) # 1.0.0
library(tidyr)
df1 %>%
group_by(Date, Market) %>%
group_by(Revenue = c(Quantity %*% Price),
TotalCost = c(Quantity %*% Cost),
Product, .add = TRUE) %>%
summarise(Sold = sum(Quantity)) %>%
pivot_wider(names_from = Product, values_from = Sold)
# A tibble: 2 x 7
# Groups: Date, Market, Revenue, TotalCost [2]
# Date Market Revenue TotalCost Apple Banana Orange
# <chr> <chr> <dbl> <dbl> <int> <int> <int>
#1 6/24/2020 A 135 37.5 35 20 20
#2 6/25/2020 A 25 15 10 15 NA
df1 <- structure(list(Date = c("6/24/2020", "6/24/2020", "6/24/2020",
"6/24/2020", "6/25/2020", "6/25/2020"), Market = c("A", "A",
"A", "A", "A", "A"), Salesman = c("MF", "RP", "RP", "FR", "MF",
"MF"), Product = c("Apple", "Apple", "Banana", "Orange", "Apple",
"Banana"), Quantity = c(20L, 15L, 20L, 20L, 10L, 15L), Price = c(1L,
1L, 2L, 3L, 1L, 1L), Cost = c(0.5, 0.5, 0.5, 0.5, 0.6, 0.6)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.