[R] "For" loop and "if" question

Steven Ranney steven.ranney at gmail.com
Wed Dec 19 21:42:18 CET 2012

All -

I have a large data frame that looks like

ID     p1     p2     p3...p20     Lat1     Lat2     Lat3...Lat20
Long1     Long2     Long3...Long20
1       0      0      1      0        NA       NA       29.xx NA
 NA          NA         -89.xx   NA
2       1      0      0      1        27.xx   NA       NA     29.00
 -88.00     NA         NA        -89.xx
3       0      0      0      0        NA      NA       NA      NA
  NA         NA          NA       NA

where length(ID) = 1300 and the zeroes and ones in the p1-p20 column
correspond to values in the Lat1-Lat20 and Long1-Long20 columns; a 0
indicates no corresponding value and 1 indicates there is a
corresponding value.

I'd like to create a dataframe that is

ID          p     Lat     Long
1           3     29.xx  -89.xx
2           1     27.xx  -88.xx
2           20   29.xx  -89.xx

and so on, such that for every ID I have, there is a corresponding row
with each Latn and Longn that may exist.

My problem is that I don't know how to do that in R.  I can set up
simple "for" loops, but I don't know how to set up something that has
a "for" and an "if/else" statement.  And frankly, with the number of
pX, LatX, and LongX, I think that my if/else statement would be huge
and unwieldly.

Could anyone offer any assistance?

Thanks for your help -

Steven H. Ranney

More information about the R-help mailing list