如何将(x,y)分离为R中的新列x和y?

问题描述 投票:-1回答:3

数据集(CSV)文件的列纬度和经度为(33,-118),(34,-119),(36,-120)等。有一百万行。

例如,如何创建两个具有lat和long单独值的新列。我知道如何使用给定的lat和long在单独的列中使用ggmap进行映射。

谢谢您的帮助

r ggplot2 ggmap
3个回答
1
投票

data.table中:

library(data.table)
setDT(myData)
myData[ , c('lat', 'lon') := tstrsplit(
  gsub('[()]', '', lat_lon_col), 
  split = ', ', 
  fixed = TRUE, type.convert = TRUE
)]

1
投票

您可以从列中提取数字并创建两个新列。

df[c('lat', 'lon')] <- stringr::str_extract_all(df$col, "-?\\d+", simplify = TRUE)
df

#         col lat  lon
#1 (33, -118)  33 -118
#2 (34, -119)  34 -119
#3 (36, -120)  36 -120

数据

df <- data.frame(col = c('(33, -118)', '(34, -119)', '(36, -120)'))

0
投票

再次尝试:

library(tidyverse)

df <- data.frame(col = c('(33, -118)', '(34, -119)', '(36, -120)'))

df %>% 
  mutate(col =col %>% str_sub(2,-2)) %>%  # remove ( and )
  separate(col, c('lat', 'lon'), convert=T) # separate


  lat lon
1  33 118
2  34 119
3  36 120
© www.soinside.com 2019 - 2024. All rights reserved.