R中的单独值(表)

oipij1gg  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(79)

我有一个由位置值(长纬度)组成的表,如下所示:

如何在R中编写代码来分隔这个long和lat值我已经使用了func separate,但返回错误(它是chr数据类型)。但是当我把它改为numb和Int时,它返回NA。
谢谢你的帮助

separate(df, col=Vehicle.Location, into=c('long', 'lat'), sep='-')
gwbalxhn

gwbalxhn1#

您的字符列是点坐标的所谓已知文本(WKT)表示。您可以将其保留为文本并从中提取组件,或者将其转换为适当的空间对象,如下所示:

library(tidyverse)
library(sf)
#> Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE

df <- tribble(
  ~DOL.Vehicle.ID, ~Vehicle.Location,
  249675142, "POINT (-122.34301 47.659185)"
)

# convert WKT representation to geometry and extract coordinates
st_coordinates(st_as_sfc(df$Vehicle.Location))
#>             X        Y
#> [1,] -122.343 47.65919

# extract from text
df |> 
  separate_wider_delim(
    Vehicle.Location,
    delim = " ",
    names = c("point", "long", "lat")
  ) |> 
  mutate(across(c(long, lat), parse_number)) |> 
  select(!point)
#> # A tibble: 1 × 3
#>   DOL.Vehicle.ID  long   lat
#>            <dbl> <dbl> <dbl>
#> 1      249675142 -122.  47.7

创建于2023-10-08带有reprex v2.0.2

wwtsj6pe

wwtsj6pe2#

一个受dufei启发的解决方案,但只使用了tidyr库。将表放入ev运行后

ev <- separate_wider_delim(ev, Vehicle.Location,delim=" ",names=c("point","long","lat"))

ev <- ev[,-2] # remove the 'point' column

ev$long <- substring(ev$long,2)
ev$lat <- substring(ev$lat,1,nchar(ev$lat)-1)

ev

## A tibble: 3 × 3
#  DOL.Vehicle.ID long         lat       
#           <dbl> <chr>        <chr>     
#1      249675142 -122.34301   47.659185 
#2      233928502 -122.20578   47.762405 
#3      229675939 -120.6027202 46.5965625

如果数据类型必须是numeric,那么也运行这个:

ev$long <- as.numeric(ev$long)
ev$lat <- as.numeric(ev$lat)

相关问题