[R] Automatically naming subsets in a for loop

jim holtman jholtman at gmail.com
Fri Jan 31 22:34:44 CET 2014


Here is one way by just truncating your data to integers based on what
you are doing:

> # create some test data
> n <- 1000
> G <- data.frame(Lat = runif(n, 38, 50), Long = runif(n, -72, -65))
> # add a 'key' for segment - based on truncating data
> G$key <- paste(as.integer(G$Lat), as.integer(G$Long), sep = ":")
> # number of unique keys
> length(unique(G$key))
[1] 84
> # split into segments
> segs <- split(G, G$key)
>
> head(G, 20)
        Lat      Long    key
1  41.59301 -68.76338 41:-68
2  46.49720 -66.33649 46:-66
3  45.53748 -68.03110 45:-68
4  39.66539 -68.20521 39:-68
5  39.82959 -71.26644 39:-71
6  41.44688 -70.43106 41:-70
7  43.71112 -66.73736 43:-66
8  44.88753 -69.75961 44:-69
9  44.50466 -71.77183 44:-71
10 46.40642 -65.00966 46:-65
11 47.80190 -65.48757 47:-65
12 40.46522 -68.00612 40:-68
13 40.98004 -71.48152 40:-71
14 49.57253 -66.71064 49:-66
15 49.22970 -69.04267 49:-69
16 48.63010 -68.33392 48:-68
17 43.20188 -67.70121 43:-67
18 46.42424 -68.34635 46:-68
19 49.46040 -70.26964 49:-70
20 40.10401 -65.23893 40:-65
>

Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.


On Fri, Jan 31, 2014 at 3:11 PM, denys <denys at uoguelph.ca> wrote:
> Hello,
>
> I'm trying to subet my data based on long/lat. I have written a for loop
> however I am not sure how to get R to name all my subsets different things.
> Here is my code so far...
>
> for(i in 0:31){
> latl=38+(i*1)
> latu=39+(i*1)
> for(j in 0:33){
> longl=(-72)+(j*1)
> longu=(-71)+(j*1)
> G$i$j<-subset(G, Lat>latl & Lat<latu & Long>longl & Long<longu)
> }
> }
>
> However this just freezes my computer.
> Any help is appreciated!
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Automatically-naming-subsets-in-a-for-loop-tp4684518.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list