gpt4 book ai didi

r - 如何通过唯一ID将R中列中的某些行添加在一起?

转载 作者:行者123 更新时间:2023-12-02 02:51:19 25 4
gpt4 key购买 nike

我是新人,如果我的问题措辞不好,我很抱歉。

我在 r 中工作,我有一个名为 Rent 的表,可能如下所示:

Rent
ID Invoice Payment Paid Date
lucy 7/1/2018 100 9/1/2018
lucy 7/1/2018 150 10/1/2018
lucy 8/1/2018 100 11/1/2018

所以我想做的是,由于 Lucy 在 7/1/2018 有两笔付款,我想将它们合并在一起,然后对付款求和,并使用最新的付款日期。

到目前为止我所拥有的是

#to create a row that has the sum of the sales prices 

Rent[,sum_late:=sum( as.numeric(("Sales Price"))),
by= c("Id","Invoice Date")]

#take the first of the unique IDs by the max paid date
head (SD,1) by=c("ID", "Invoice Date", max("Paid Date")

但是当我运行第一行时,所有 sum_late 列都是 N/A。我不确定我做错了什么。理想情况下,我想要一张像这样的 table 。

Rent
ID Invoice Payment Paid Date
lucy 7/1/2018 250 10/1/2018
lucy 8/1/2018 100 11/1/2018

抱歉,如果这是一个愚蠢的问题,我感谢任何帮助和反馈!谢谢大家的宝贵时间!

最佳答案

我们可以将 Paid_Date 更改为日期类、group_by IDInvoicesum Payment 并选择 max Paid_Date

library(dplyr)
Rent %>%
mutate_at(vars(Invoice, Paid_Date), as.Date, '%d/%m/%Y') %>%
group_by(ID, Invoice) %>%
summarise(Payment = sum(Payment),
Paid_Date = max(Paid_Date))

# ID Invoice Payment Paid_Date
# <chr> <date> <int> <date>
#1 lucy 2018-01-07 250 2018-01-10
#2 lucy 2018-01-08 100 2018-01-11

或者,如果您更喜欢使用相同逻辑的data.table

library(data.table)
setDT(Rent)[, c("Invoice", "Paid_Date") := .(as.IDate(Invoice, '%d/%m/%Y'),
as.IDate(Paid_Date, '%d/%m/%Y'))]
Rent[, .(Payment = sum(Payment), Paid_Date = max(Paid_Date)), .(ID, Invoice)]

数据

Rent <- structure(list(ID = c("lucy", "lucy", "lucy"), Invoice = c("7/1/2018", 
"7/1/2018", "8/1/2018"), Payment = c(100L, 150L, 100L), Paid_Date = c("9/1/2018",
"10/1/2018", "11/1/2018")), class = "data.frame", row.names = c(NA, -3L))

关于r - 如何通过唯一ID将R中列中的某些行添加在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61928296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com