R: assign values to set of vectors based on conditions in another data frame of different length -
i assign segment-id longitude , latitude values fall within range of minimum/maximum long , lat values stored in different data frame of different length. data looks this: data frame observations:
head(obs) longitude latitude 52.06264 6.412816 52.06097 6.413106 51.06097 6.413346 54.06097 6.413276 51.06089 6.413114 52.05444 6.413094
data frame ranges , segment-id:
head(seg) segment lon_max lon_min lat_max lat_min 01a 6.857822 6.857476 51.05837 51.03489 01b 6.858979 6.857834 51.03433 50.99901 01c 6.860019 6.858982 51.99836 51.96330 01d 6.860960 6.860050 51.96277 51.92718 01e 6.862294 6.860979 51.92657 51.89125 01f 6.863179 6.862301 51.89059 51.85562
for each point of observation know within 'segment' falls, ideally end this:
longitude latitude segment 52.03464 6.458816 1a 52.05667 6.416606 1a 51.06097 6.446346 1b 54.03757 6.413276 1c 51.06089 6.422114 1b 52.34243 6.413094 1a
i have tried using latitude, error message, due different length of vectors.
obs[['segment']] <- (i in obs$latitude) { if (i>=seg$lat_min & i<=seg$lat_max) { obs$segment=seg$segment } else { obs$segment='na'} } error in `$<-.data.frame`(`*tmp*`, "segment", value = 1:118) : replacement has 118 rows, data has 10284
i realise why can't work because doesn't match row row, don't know how this. how can match each pair of latitude , longitude row row min/max values until find range fits , assign correct segment_id?
thanks in advance!
given vector x
components "longitude" , "latitude", function f
uses which.max
find appropriate row in seg
. apply(obs,1,f)
vector of length nrow(obs)
contains row numbers of appropriate segments in seg
:
obs <- read.table( header = true, text = "latitude longitude 52.06264 6.412816 51.90089 6.861084 52.06097 6.413106 51.06097 6.413346 54.06097 6.413276 51.04097 6.857576 51.06089 6.413114 51.95089 6.860084 52.05444 6.413094" ) seg <- read.table( header = true, stringsasfactors = false, text = "segment lon_max lon_min lat_max lat_min 01a 6.857822 6.857476 51.05837 51.03489 01b 6.858979 6.857834 51.03433 50.99901 01c 6.860019 6.858982 51.99836 51.96330 01d 6.860960 6.860050 51.96277 51.92718 01e 6.862294 6.860979 51.92657 51.89125 01f 6.863179 6.862301 51.89059 51.85562") f <- function(x) { which.max( c( ( seg["lon_min"] <= c(x["longitude"]) ) & ( seg["lon_max"] > c(x["longitude"]) ) & ( seg["lat_min"] <= c(x["latitude"]) ) & ( seg["lat_max"] > c(x["latitude"]) ), true ) ) } x <- cbind( obs, segment = seg$segment[apply(obs,1,f)] )
result:
> x latitude longitude segment 1 52.06264 6.412816 <na> 2 51.90089 6.861084 01e 3 52.06097 6.413106 <na> 4 51.06097 6.413346 <na> 5 54.06097 6.413276 <na> 6 51.04097 6.857576 01a 7 51.06089 6.413114 <na> 8 51.95089 6.860084 01d 9 52.05444 6.413094 <na>
Comments
Post a Comment