0

I have one data frame/ list that gives and ID and a number

1.  25
2.  36
3.  10
4.  18
5.  12

This first list is effectively a list of objects with the number of objects contained in each eg. bricks in a wall, so a a list or walls with the number of bricks in each. I have a second that contains a a full list of the objects being referred to in that above list and a second attribute for each.

1.   3
2.   4
3.   2
4.   8
5.   5

etc. in the weak example I'm stringing together this would be a list of the weight of each brick in all walls.

so my first list give me the ranges i would like to average in the second list, or I would like as an end result a list of walls with the average weight of each brick per wall.

ie average the attributes of 1-25, 26-62 ... 89-101

my idea so far was to create a data frame with two coloumns

1. 1 25
2. 26 62
3. n
4. n
5. 89 101

and then attempt to create a third column that uses the first two as x and y in a mean(table2$coloumn1[x:y]) type formula, but I can't get anything to work.

the end result could probably looks something like this

1.   3.2
2.   6.5
3.   3
4.   7.9
5.   8.5

is there a way to do it like this or does anyone have a more elegant solution.

  • 2
    This looks like a well thought out question, but it could use better formatting, clearer expected output and a more easily reproduced example. See http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 for some guidance. – Frank Apr 25 '17 at 18:27

1 Answers1

1

You could do something like this... set the low and high limits of your ranges and then use mapply to work out the mean over the appropriate rows of df2.

df1 <- data.frame(id=c(1,2,3,4,5),no=c(25,36,10,18,12))
df2 <- data.frame(obj=1:100,att=sample(1:10,100,replace=TRUE))

df1$low <- cumsum(c(1,df1$no[-nrow(df1)]))
df1$high <- pmin(cumsum(df1$no),nrow(df2))
df1$meanatt <- mapply(function(l,h) mean(df2$att[l:h]), df1$low, df1$high)

df1
  id no low high  meanatt
1  1 25   1   25 4.760000
2  2 36  26   61 5.527778
3  3 10  62   71 5.800000
4  4 18  72   89 5.111111
5  5 12  90  100 4.454545
Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32