get values from string using strsplit and/or substring in R -
the below string character, contains information want use , assign variables.
[1] "elev: 82 m lat: 39° 37' 39\" n long: 22° 23' 55\" e"
.
for example: assign elev
variable numeric value equal 82
.
how should approach this? need regular expression using strsplit
, substring
?
here strsplit
solution.
the first argument gsub
pattern string "(\\w+):"
. matches "word" characters "\\w"
ensuring there @ least 1 such character "+"
match succeeds if word characters followed colon ":"
.
the second argument gsub
replacement string ":\\1:"
. specifies portion of pattern within parens "(\\w+)"
replaced "\\1"
followed colon ":"
. is, prefaces each word ending in :
:
.
finally strsplit
splits on spaces-colon-spaces forming result matrix. code not depend on labels are:
m <- matrix(strsplit(gsub("(\\w+):", ":\\1:", x), " *: *")[[1]][-1], 2)
giving:
> m [,1] [,2] [,3] [1,] "elev" "lat" "long" [2,] "82 m" "39° 37' 39\" n" "22° 23' 55\" e"
or alternative form:
v <- as.list(setnames(m[2,], m[1,]))
giving:
> v $elev [1] "82 m" $lat [1] "39° 37' 39\" n" $long [1] "22° 23' 55\" e"
which can used this:
v$elev
Comments
Post a Comment