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!

Answers


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

Need Your Help

Node.js connect not serving images correctly

javascript image node.js connect httpserver

I am currently trying to write a very simple webserver using Node.js and connect, that basically just serves a single directory staticly.

how to check in sqlite3 whether number of columns are changed or not

c++ c linux sqlite gcc

Iam coding in c and using sqlite3 as database .I want to ask that how can we check whether no. of columns in a table got changed or not. Situation is like this that i am going to run the applicatio...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.