[英]How to aggregate Character Data of a data frame based on different column in r
[英]data frame aggregate and keep character column
我有數據框
ID type Count Out
1 A 1 11
2 A 2 12
2 B 5 10
3 B 3 10
3 B 5 7
3 C 1 5
預期的結果是
ID type Count(sum) Out (sum)
1 A 1 11
2 AB 7 22
3 BBC 9 22
我正在嘗試聚合函數,但是沒有類型列就可以實現結果表。
我想知道是否有一種方法可以保留預期結果表中顯示的字符。
ID <- c(1,2,2,3,3,3)
type <- c("A","A","B", "B", "B","C")
Count <- c( 1,2,5,3,5,1)
out <- c(11,12,10,12,7,5)
x <- as.data.frame(cbind(ID,Count,out))
result <- aggregate(x, list(x$ID), sum_col)
您可以在C#中使用Linq來實現您正在描述的操作。 我構建了以下Linq查詢,以顯示此操作。 它在第二列中保持順序,因為內部使用的是就地算法。 主要是我使用了GroupBy
Linq運算符以及String.Join
和Sum
聚合函數來解決問題。
void Main()
{
var data = new[] {
new { Id = 1, Type = "A", Count = 1, Out = 11 },
new { Id = 2, Type = "A", Count = 2, Out = 12 },
new { Id = 2, Type = "B", Count = 5, Out = 10 },
new { Id = 3, Type = "B", Count = 3, Out = 10 },
new { Id = 3, Type = "B", Count = 5, Out = 7 },
new { Id = 3, Type = "C", Count = 1, Out = 5 },
};
var result = data
.GroupBy(d => d.Id)
.Select(g => new
{
Ids = g.Key,
Types = String.Join(String.Empty, g.Select(x => x.Type).ToArray()),
Counts = g.Sum(d => d.Count),
Outs = g.Sum(d => d.Out)
})
.ToList();
result.ForEach(r => Console.WriteLine($"{r.Ids} {r.Types} {r.Counts} {r.Outs}"));
}
這將返回以下內容:
1 A 1 11
2 AB 7 22
3英國廣播公司9 22
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.