R 数据框 : add values in common rows

标签 r list dataframe

我有一个这样的数据框。

> 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/

相关文章:

R SQLite 在使用 COUNT 时将 char 转换为数字

algorithm - 构造无限排序列表而不添加重复项

python - 使用多维数组中的每个第一个元素

list - CMake 在命令行上传递列表

python - 将字典列表的字典转换为数据框

r - 根据 r 中的第三列及时将值复制到下一行

R:计算 log(exp(...)) 的最大浮点误差

R 检查重复项非常慢,即使使用 mclapply

r - 如何从不匹配的数据框中选择行?

python - 如何根据 Python 中另一列的条件复制字段?