[R] Data Subsetting - First/Before/Last conditions

arun smartpink111 at yahoo.com
Mon Mar 24 20:13:26 CET 2014


Hi,
May be this helps:
val <- with(mydataset, diff(Lat))

indx <- cumsum(c(TRUE,val!=0 & !is.na(val)))

mydataset$Tr[indx==1]
#[1] 3 5 2 5
 sum(mydataset$Tr[indx==1])
#[1] 15
 mydataset$Tr[indx<=2]
#[1] 3 5 2 5 6
 sum(mydataset[indx==6,-2])
#[1] 12.5
#or
sum(mydataset[indx==rev(unique(indx))[2],-2])
[1] 12.5

A.K.


Dear R-Helpers, 

I am analyzing a data frame that has the same structure as the example below ("mydataset"): 

Ti	Tr	Lat 
1	3	0 
2	5	0 
3	2	0 
4	5	0 
5	6	0.1 
6	7	0.2 
7	1	0.5 
8	4	0 
9	2.5	0 
10	3.5	0 
11	2.7	0 
12	3.3	0.5 
13	5	0 
14	4	0 
NA	NA	NA 
14	54	5.1 
NA	NA	NA 
NA	NA	NA 


I am trying to perform the following tasks: 

1. Extraction of all the values of "Tr" before the values of "Lat" differ for the first time from "0". 

mydataset$Tr[mydataset$Lat==0] does obviously not help, because it extracts every value of "Tr" for "Lat" equal to zero. 

In this case ("mydataset") the values to be extracted are: 3.0, 5.0, 2.0, 5.0, which I would sum to obtain 15.0. 

2. Same procedure as above, but including the first non-zero value of "Lat". 

"mydataset" values are: 3.0, 5.0, 2.0, 5.0, 6.0 which I would sum (21.0). 

3. Extraction of the last value of "Lat" that is different from 
"0" and that appears before the first "NA" (in this case "0.5"); sum it 
with the corresponding value of "Ti" ("12") to obtain 12.5. 

I have spent some time looking around on the web, but I was not able to find the answers I need. 

Any help? Thank you a lot! 




More information about the R-help mailing list