簡體   English   中英

由R合並的拆分(x,y)坐標

[英]Split (x,y) coordinates that were combined by R

我有一個在R中導入數據時合並的列。該列中的數據看起來像是c(-122.430061, 37.785553) 我如何將其分為僅兩列longlat

數據如下所示:

#dput(coords[1:5,])
structure(list(type = c("Point", "Point", "Point", "Point", "Point"
), coordinates = list(c(-122.191986, 37.752671), c(-122.20254, 
37.777845), c(-122.250701, 37.827707), c(-122.270252, 37.806838
), c(-122.259369, 37.809819))), .Names = c("type", "coordinates"
), row.names = c(1L, 2L, 3L, 5L, 6L), class = "data.frame")

好吧,查看數據后,這似乎是正確的方法:

x <- structure(list(type = c("Point", "Point", "Point", "Point", "Point"
), coordinates = list(c(-122.191986, 37.752671), c(-122.20254, 
37.777845), c(-122.250701, 37.827707), c(-122.270252, 37.806838
), c(-122.259369, 37.809819))), .Names = c("type", "coordinates"
), row.names = c(1L, 2L, 3L, 5L, 6L), class = "data.frame")

x$coordinates不是字符串列,而是一個列表:

#[[1]]
#[1] -122.19199   37.75267
#
#[[2]]
#[1] -122.20254   37.77784
#
#[[3]]
#[1] -122.25070   37.82771
#
#[[4]]
#[1] -122.27025   37.80684
#
#[[5]]
#[1] -122.25937   37.80982

我們可以將sapply"["

long <- sapply(x$coordinates, "[", 1)
# [1] -122.1920 -122.2025 -122.2507 -122.2703 -122.2594

lat <- sapply(x$coordinates, "[", 2)
# [1] 37.75267 37.77784 37.82771 37.80684 37.80982

但是,更有效的方法是通過以下原始答案中的技巧:

xx <- unlist(x$coordinates)

long <- xx[seq(1,length(xx),2)]
# [1] -122.1920 -122.2025 -122.2507 -122.2703 -122.2594

lat <- xx[-seq(1,length(xx),2)]
# [1] 37.75267 37.77784 37.82771 37.80684 37.80982

原始答案

我認為這可能是您正在尋找的,假設您有一個字符列(如果目前是一個因素, as.character使用as.character進行強制):

## example column
x <- c("12.3, 15.2", "9.2,11.1", "13.7,22.5")
#[1] "12.3, 15.2" "9.2,11.1"   "13.7,22.5"

xx <- scan(text = x, what = numeric(), sep = ",")
#[1] 12.3 15.2  9.2 11.1 13.7 22.5

long <- xx[seq(1,length(xx),2)]
#[1] 12.3  9.2 13.7

lat <- xx[-seq(1,length(xx),2)]
#[1] 15.2 11.1 22.5

如果您不想重新運行導入。 library(tidyr)為此seperate()提供了很好的功能

datf <- tidyr::separate(datf, coordinates, into = c("long", "lat"), sep = ",")
datf$long <- gsub("c\\(", "", datf$long)
datf$lat <- gsub("\\)", "", datf$lat)

gsub()清理工作有點麻煩,但是可以完成工作。 也許有人可以改善我的separate通話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM