簡體   English   中英

匯總子組中的特定條目(R編程)

[英]Summing up specific entries in subset group (R programming)

所以基本上我有這種數據格式:

ID  Value
1   32
5   231
2   122
1   11
3   ...
2   ...
5   ...
6   ...
2   ...
1   33
.   ...
.   ...
.   ...

我想對ID為'1'的值求和,但以5為一組。即在前5個條目中,有2個ID為'1'的條目,所以我得到一個總和43,然后在下一個5條目,只有一個條目具有ID'1',所以我得到33。依此類推...因此,最后我想得到一個包含所有和的數組,即(43,33,......)

我可以使用for循環和tapply來做到這一點,但我認為R中必須有一種不需要for循環的更好方法

任何幫助深表感謝! 非常感謝你!

新建一個列以反映5組:

df = data.frame(
  id = sample(1:5, size=98, replace=TRUE),
  value = sample(1:98)
)
# This gets you a vector of 1,1,1,1, 2,2,2,2,2, 3, ...
groups = rep(1:(ceiling(nrow(df) / 5)), each=5)
# But it might be longer than the dataframe, so:
df$group = groups[1:nrow(df)]

然后,很容易就可以得出每個組中的總和:

library(plyr)
sums = ddply(
  df,
  .(group, id),
  function(df_part) {
    sum(df_part$value)
  }
)

輸出示例:

> head(df)
  id value group
1  4    94     1
2  4    91     1
3  3    22     1
4  5    42     1
5  1    46     1
6  2    38     2
> head(sums)
  group id  V1
1     1  1  46
2     1  3  22
3     1  4 185
4     1  5  42
5     2  2  55
6     2  3 158

這樣的事情會做的工作:

m <- matrix(d$Value, nrow=5)

# Remove unwanted elements
m[which(d$ID != 1)] <- 0

# Fix for short data
if ((length(d$Value) %/% 5) != 0)
  m[(length(d$Value)+1):length(m)] <- 0

# The columns contain the groups of 5
colSums(m)

如果添加一列來描述組,則ddply()可以神奇地工作:

ID <- c(1, 5, 2, 1, 3, 2, 5, 6, 2, 1)
Value <- c(32, 231, 122, 11, 45, 34, 74, 12, 32, 33)
Group <- rep(seq(100), each=5)[1:length(ID)]

test.data <- data.frame(ID, Value, Group)

library(plyr)
output <- ddply(test.data, .(Group, ID), function(chunk) sum(chunk$Value))


> head(test.data)
   ID Value Group
1   1    32     1
2   5   231     1
3   2   122     1
4   1    11     1
5   3    45     1
6   2    34     2

> head(output)
  Group ID  V1
1     1  1  47
2     1  2 125
3     1  3  49
4     1  5 237
5     2  1  36
6     2  2  74

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM