Ricardo Miranda
Ricardo Miranda

Reputation: 23

How to convert data.frame to SpatialPolygonsDataFrame

Maybe it is something simple but I am stumped right now. I have a SpatialPolygonsDataFrame which I extract the data columns and transform it into a standard dataframe. Then, I round the data. But, when I want to insert the data already rounded back into the SpatialPolygonsDataFrame, I see that it keeps the data as it was originally, without being rounded. Here is my code.

Hex_Grid_Pop <- readOGR(dsn=".", layer="Hex_Grid_500_Pop")
df = as.data.frame(Hex_Grid_Pop)[, 3:13]
df %>% mutate_if(is.numeric, round)
Hex_Grid_Pop[1:NROW(Hex_Grid_Pop), 3:13] = df
head(Hex_Grid_Pop@data)

This is what my console shows me Sorry but I dont have the enough reputation to publish images.

Upvotes: 1

Views: 283

Answers (1)

Ben Toh
Ben Toh

Reputation: 782

You need to assign df to df %>% mutate_if(is.numeric, round), i.e.

df <- df %>% mutate_if(is.numeric, round)

Otherwise you df remained unchanged.

Also, nothing stops you from doing this:

Hex_Grid_Pop@data[,3:13] <- Hex_Grid_Pop@data[,3:13] %>% mutate_if(is.numeric, round)

Upvotes: 0

Related Questions