Guilherme Frediani
Guilherme Frediani

Reputation: 35

Separate and use values in r

So, im trying to separate the values from this column of a datased that has Latitude and Longitude together. This is how the values are separated

df <- data.frame(localidade = c(drugs_location))
df %>% separate(localidade, c("Lat", "Long"), sep = ",")

I used this code above to separate the values in Lat and Long but now i need to use those values to make a plot using the Lat as the x axis and Long as the y axis.

This is the dput(head(df)) output as requested:

    structure(list(localidade = c("(42.30676881, -71.08431925)", 
"(42.30676881, -71.08431925)", "(42.33152148, -71.07085307)", 
"(42.31580934, -71.07618683)", "(42.31580934, -71.07618683)", 
"(42.31224532, -71.07317861)")), row.names = c(NA, 6L), class = "data.frame")

Upvotes: 0

Views: 60

Answers (1)

Wawv
Wawv

Reputation: 381

library(stringr) 
library(dplyr)
df %>%
  mutate(localidade = str_replace_all(localidade, "\\(|\\)", "")) %>%
  separate(localidade, c("Lat", "Long"), sep = ",") %>%
  mutate(Lat = as.numeric(Lat), Long = as.numeric(Long))

You need to convert the values to numeric. The first mutate deletes all the "(" or ")" from the string.
Then you seperate the string with the "," and convert to numeric.

Upvotes: 1

Related Questions