nenno lillo
nenno lillo

Reputation: 637

R: divide a factor or string variable into two new variables

Hi everyone, I have a dataframe with a column called the_geom_OBJECTID which presents a factorial variable.

                               the_geom_OBJECTID 
                                           <fct>
1   POINT  (-73.8472005205491 40.89470517661004) 
2  POINT  (-73.82993910812405 40.87429419303015) 
3  POINT  (-73.82780644716419 40.88755567735082) 
4 POINT  (-73.90564259591689 40.895437426903875) 
5  POINT  (-73.91258546108577 40.89083449389134) 
6  POINT  (-73.90281798724611 40.88168737120525)

I would like to replace the column of this data frame with two columns, one for longitude and another for latitude

expected output:

           longitude            latitude
               <dbl>               <dbl>
1  -73.8472005205491   40.89470517661004
2 -73.82993910812405   40.87429419303015
3 -73.82780644716419   40.88755567735082
4 -73.90564259591689  40.895437426903875
5 -73.91258546108577   40.89083449389134
6 -73.90281798724611   40.88168737120525

would it be better to transform the variable into a string format to then create the two new columns?

Upvotes: 3

Views: 225

Answers (1)

mharinga
mharinga

Reputation: 1780

The easiest way to achieve this is using sf::st_coordinates():

sf::st_coordinates(the_geom_OBJECTID)

Update:

Convert your data frame to a sf object first.

library(sf)

df <- data.frame(the_geom_OBJECTID = c("POINT  (-73.8472005205491 40.89470517661004)", 
                                       "POINT  (-73.82993910812405 40.87429419303015)", 
                                       "POINT  (-73.82780644716419 40.88755567735082)", 
                                       "POINT  (-73.90564259591689 40.895437426903875)", 
                                       "POINT  (-73.91258546108577 40.89083449389134)", 
                                       "POINT  (-73.90281798724611 40.88168737120525)"))

df_sf <- st_sf(st_as_sfc(df$the_geom_OBJECTID))

Then:

sf::st_coordinates(df_sf)

Upvotes: 1

Related Questions