user2341380
user2341380

Reputation: 15

Summing up specific entries in subset group (R programming)

So basically I have this format of data:

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

I want to sum up the values with ID '1', but in a group of 5. i.e. In the first 5 entries, there are 2 entries with ID '1', so i get a sum 43, and then in the next 5 entries, only one entry have ID '1', so i get 33. and so on... so at the end I want to get a array with all the sums, i.e. (43,33,......)

I can do it with for loop and tapply, but I think there must be a better way in R that doesnt need a for loop

Any help is much appreciated! Thank you very much!

Upvotes: 0

Views: 196

Answers (3)

Andrew
Andrew

Reputation: 38629

If you add a column to delineate groups, ddply() can work magic:

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

Upvotes: 0

Marius
Marius

Reputation: 60070

Make a new column to reflect the groups of 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)]

Then it's pretty easy to get the sums within each group:

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

Example output:

> 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

Upvotes: 1

Matthew Lundberg
Matthew Lundberg

Reputation: 42649

Something like this will do the job:

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)

Upvotes: 0

Related Questions