I have data with 2 sets of coordinates and other variables.
How can I convert two sets of coordinates into SpatialPoint data frame?
From To Dist xFrom yFrom xTo yTo
BARINGO BOMET 1.7019462 35.9659 0.819193 35.3146 -0.753203
BARINGO BONDO 1.9648836 35.9659 0.819193 34.2529 -0.143303
BARINGO BUNGOMA 1.3139522 35.9659 0.819193 34.6606 0.668653
I have two sets of coordinates (xFrom,yFrom) and (xTo,yTo) and have tried the below codes which are not working
library(sp)
df <- sample[-4:-7]
xy1 <- sample[4:5]
xy2 <- sample[6:7]
SPDF <- SpatialPointsDataFrame(coords=xy1, coords=xy2, data=df)
I apologize in advance to mistake your question and do wrong edit.
coords
should be one matrix
or data.frame
, and nrow(data)
should equal the number of points.
xy1.1 <- as.matrix(xy1)
xy2.1 <- as.matrix(xy2) # rbind(xy1, xy2) doesn't run because of difference colnames.
xy12 <- rbind(xy1.1, xy2.1)
df2 <- rbind(df, df)
SPDF <- SpatialPointsDataFrame(coords = xy12, data = df2)
[Edited]
you can filter SpatialPointsDataFrame
data using its data.frame
.
df1 <- data.frame(df, Attribute = rep("from", nrow(df)), ID = 1:nrow(df)) df2 <- data.frame(df, Attribute = rep("to", nrow(df)), ID = 1:nrow(df)) xy12 <- rbind(as.matrix(xy1), as.matrix(xy2)) df12 <- rbind(df1, df2) SPDF <- SpatialPointsDataFrame(xy12, data = df12) # sort.list <- order(SPDF@data$ID) # sorted.SPDF <- SPDF[sort.list,] head(SPDF, n=4) # coordinates From To Dist Attribute ID # 1 (35.9659, 0.819193) BARINGO BOMET 1.701946 from 1 # 2 (35.9659, 0.819193) BARINGO BONDO 1.964884 from 2 # 3 (35.9659, 0.819193) BARINGO BUNGOMA 1.313952 from 3 # 4 (35.3146, -0.753203) BARINGO BOMET 1.701946 to 1 SPDF[SPDF@data$Attribute == "from",] # only "from" SPDF[SPDF@data$Attribute == "to",] # only "to" # ind1 <- which(SPDF@data$Attribute == "from") plot(SPDF, col="#00000000") # a draft to set coordinates plot(SPDF[SPDF@data$Attribute=="from",], col=2, add=T) # plot(SPDF[ind1,], col=2, add=T) plot(SPDF[SPDF@data$Attribute=="to",], col=4, add=T)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.