gpt4 book ai didi

R 数据框 : add values in common rows

转载 作者:行者123 更新时间:2023-12-02 06:36:01 26 4
gpt4 key购买 nike

我有一个这样的数据框。

> df1
portfolio date ticker quantity price
1 port 2010-01-01 AAPL 100 10
2 port 2010-01-01 AAPL 200 10
3 port 2010-01-01 AAPL 400 11

如果df1中除quantity以外的行相同,则添加共同行的quantity。我的意思是,我需要以下输出

portfolio       date ticker quantity price
1 port 2010-01-01 AAPL 300 10
3 port 2010-01-01 AAPL 400 11

我该怎么做?谢谢..

最佳答案

给你...:-)

对于 plyr :

ddply(df, .(portfolio, date, ticker, price),summarize, quantity=sum(quantity))

对于 data.table :

dt <- data.table(df)
dt[,list(quantity=sum(quantity)),by=list(portfolio,date,ticker,price)]

可能有更简洁的方式来表达分组变量列表。否则,聚合 解决方案要优雅得多。

关于R 数据框 : add values in common rows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914669/

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