根据R中的其他数据框列创建新的数据框

问题描述 投票:-1回答:1

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

我的新数据框(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")
)

任何帮助将不胜感激。

r dataframe subset
1个回答
0
投票

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

我使用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
© www.soinside.com 2019 - 2024. All rights reserved.