1

I have lots of data frame like the one below. I need to find the Total in last sample just before weight value is zero. here for example in the sample of 7 I need to find the weight that is 6.

Sample Weight Total
1       2     0
2       3     0 
3       7     0
4       5     4
5       4     3
6       3     8
7       6     12
8       0     11
9       0     8
10      0     9

Here is what i have tried:

New.DF <- DF$Total [ Weight > 0, Sample=max]
1
  • Can u show the expected otuput Commented Jun 1, 2017 at 9:50

1 Answer 1

1

We need to extract the column

 with(DF, max(Sample[Weight!=0]))
 #[1] 7

Or may be

library(data.table)
setDT(DF)[Weight!=0, .SD[.N] ,.(grp = rleid(Weight==0))]
#      grp Sample Total
#1:     1      7    12
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for answer, i tried first but why these two give me different answer?b <-with(df, max(Sample[EZ!=0])) c<- df$Sample[ with(df, max(Sample[EZ!=0]))]
@Mori It is because you are subsetting the Sample and then use it as an index in the 2nd case, which is not right. INstead you may need i1 <- with(df, Sample == max(Sample[EZ !=0])) and use that to subset

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.