首页 > 解决方案 > 基于 R 中其他数据框的列创建新数据框

问题描述

我正在尝试从现有数据框创建一个新的数据框:

我的新数据框 ( new_dataframe) 将包含两个特定类别(c1 和 c2)的特定年份(2017 年)的每月购买量。知道这一点,我的其他数据框是:

我试过了substract()aggregate()但它对我不起作用。
例如,要获取特定年份的数据(只是解决方案的一部分),我使用了以下代码:

new_dataframe <- subset(
  AllInfosClients, 
  AllInfosClients$Date_achat == as.Date(AllInfosClients$Date_acha,"%d/%m/2017")
)

任何帮助将不胜感激。

标签: rdataframesubset

解决方案


这是一个整洁的解决方案。

我曾经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

推荐阅读