Import or parse a list into R

I have a CSV file in which one of the fields contains some saved coordinates:

"TRIP_ID","COORDINATES"

"T1","[[-8.585676,41.148522],[-8.585712,41.148639],[-8.585685,41.148855],[-8.58573,41.148927],[-8.585982,41.148963]]"

"T2","[[-8.610876,41.14557],[-8.610858,41.145579],[-8.610903,41.145768]]"

...

When I import this into R, I get a data frame with two columns. The problem is with the COORDINATES column class. Both charachters or fragments are of little use in my case.

I want to ensure that this data is stored in a list or in a vector, so I can write something like df $ COORDINATES [1] [1] AND GET -8.585676,41.148522 .

How can i do this? Thank you for your help:)

+4
source share
2 answers

It looks like a JSON notation for nested lists. So you can use one of the JSON packages:

tmp.txt='"TRIP_ID","COORDINATES"
"T1","[[-8.585676,41.148522],[-8.585712,41.148639],[-8.585685,41.148855],[-8.58573,41.148927],[-8.585982,41.148963]]"
"T2","[[-8.610876,41.14557],[-8.610858,41.145579],[-8.610903,41.145768]]"
'

 df = read.csv(text=tmp.txt,stringsAsF=FALSE)

:

> require(jsonlite)
> fromJSON(df$COORDINATES[2])
          [,1]     [,2]
[1,] -8.610876 41.14557
[2,] -8.610858 41.14558
[3,] -8.610903 41.14577

, , . :

Clist = lapply(df$COORDINATES, fromJSON)

, , :

> Clist[[1]]
          [,1]     [,2]
[1,] -8.585676 41.14852
[2,] -8.585712 41.14864
[3,] -8.585685 41.14885
[4,] -8.585730 41.14893
[5,] -8.585982 41.14896
> Clist[[2]]
          [,1]     [,2]
[1,] -8.610876 41.14557
[2,] -8.610858 41.14558
[3,] -8.610903 41.14577

, , GPS- , SpatialLinesDataFrames - sp .

+3

strapply gsubfn:

> library(gsubfn)
> tmp.txt <- '"TRIP_ID","COORDINATES"
+ "T1","[[-8.585676,41.148522],[-8.585712,41.148639],[-8.585685,41.148855],[-8.58573,41.148927],[-8.585982,41.148963]]"
+ "T2","[[-8.610876,41.14557],[-8.610858,41.145579],[-8.610903,41.145768]]"
+ '
> 
> df <- read.table(text=tmp.txt, stringsAsFactors = FALSE, header=TRUE)
> 
> coords <- strapply(df$X..COORDINATES, 
+                    '\\[(-?[0-9]+\\.?[0-9]*),(-?[0-9]+\\.?[0-9]*)\\]',
+                    FUN=function(one,two) c(as.numeric(one),as.numeric(two)),
+                    combine=list)
> str(coords)
List of 2
 $ :List of 5
  ..$ : num [1:2] -8.59 41.15
  ..$ : num [1:2] -8.59 41.15
  ..$ : num [1:2] -8.59 41.15
  ..$ : num [1:2] -8.59 41.15
  ..$ : num [1:2] -8.59 41.15
 $ :List of 3
  ..$ : num [1:2] -8.61 41.15
  ..$ : num [1:2] -8.61 41.15
  ..$ : num [1:2] -8.61 41.15
> coords[[1]][[1]]
[1] -8.585676 41.148522

, ( -123) 1 , , . , , .

+3

All Articles