r - 基于 R 中其他数据框的列创建新数据框
问题描述
我正在尝试从现有数据框创建一个新的数据框:
我的新数据框 ( new_dataframe
) 将包含两个特定类别(c1 和 c2)的特定年份(2017 年)的每月购买量。知道这一点,我的其他数据框是:
- df1 = client_data (clientId, city, category)
- df2 = purchase_data (clientId, 数量, 价格, purchase_date)
我试过了substract()
,aggregate()
但它对我不起作用。
例如,要获取特定年份的数据(只是解决方案的一部分),我使用了以下代码:
new_dataframe <- subset(
AllInfosClients,
AllInfosClients$Date_achat == as.Date(AllInfosClients$Date_acha,"%d/%m/2017")
)
任何帮助将不胜感激。
解决方案
这是一个整洁的解决方案。
我曾经dplyr::full_join()
合并 df1 和 df2,将日期转换为日期格式,lubridate
然后用于dplyr::filter()
2015 年和类别 S7 和 S14:
library(dplyr)
library(lubridate)
# expected output from author's OP comment
new_dataframe <- read.table(text = "
Client Ville Category Qte Montant Date_achat
1 Cl1 Marseille S7 28 2750 16/05/2015
2 Cl1 Marseille S7 27 2570 03/06/2015
3 Cl3 Marseille S14 25 1240 21/11/2015
4 Cl3 Marseille S14 18 1560 21/10/2016
5 Cl3 Marseille S14 15 1460 30/11/2016
6 Cl5 Grenoble S15 30 1980 19/03/2016
7 Cl9 Marseille S10 22 2030 19/07/2015",
header = T,
stringsAsFactors = F) %>%
tbl_df()
# backwardly create df1 df2
df1 <- new_dataframe %>%
select(Client, Ville, Category) %>%
unique()
df2 <- new_dataframe %>%
select(Client, Qte, Montant, Date_achat)
# join data frames
full_join(df1, df2, by = "Client")
# converts date to date format
new_dataframe$Date_achat <- dmy(new_dataframe$Date_achat)
# filtered data frame
df <- new_dataframe %>%
filter(year(Date_achat) == 2015, (Category == "S7" | Category == "S14"))
# # A tibble: 3 x 6
# Client Ville Category Qte Montant Date_achat
# <chr> <chr> <chr> <int> <int> <date>
# 1 Cl1 Marseille S7 28 2750 2015-05-16
# 2 Cl1 Marseille S7 27 2570 2015-06-03
# 3 Cl3 Marseille S14 25 1240 2015-11-21
推荐阅读
- c# - 将时区信息添加到日期时间对象 C#
- visual-studio-code - 我的 Visual Studio 代码扩展未显示在侧边栏中
- android - 检测应用程序是否从最近的应用程序列表中关闭或被操作系统杀死
- jquery - 加载预选选项时隐藏和显示表单元素
- c# - 当父视图具有相同的模型时,如何在部分视图中获取 HTML 表单数据以进行序列化?
- python - 如何通过比较两个数据框来计算缺失值
- swiftui-list - SwiftUI 列表在 @ObservedObject 更新时冻结
- git - 代码被两天前提交到 github 的旧代码覆盖。我应该怎么做才能获得本地代码?
- iis - IIS 处理同一网站内多个应用程序的 url 请求
- r - 使用 source() 函数在 Linux 中导出/打印 R 图