mustafa00
mustafa00

Reputation: 881

How to make a vector (saved as a string) a vector back again?

I saved polygon coordinates to the database and this is how it's saved to a table:

c(22.841941, 23.413109, 21.831413, 22.841941, 50.134664, 49.453843, 49.353756, 50.134664)

Now, I need to read it to R and make it polygon again but the issue is that when I read coordinates from database then they are of type character (with quotation marks):

"c(22.841941, 23.413109, 21.831413, 22.841941, 50.134664, 49.453843, 49.353756, 50.134664)"   

I wanted to make it vector again c(22.841941, 23.413109,...) - remove somehow the quotations marks. I tried some string operations e.g.:

text <- "c(22.841941, 23.413109, 21.831413, 22.841941, 50.134664, 49.453843, 49.353756, 50.134664)" 
stringr::str_replace(text, "\""," ")

or:

gsub('"',"",text)

but it doesn't remove quotation marks. And sure, I also tried to make it a list by list(text) or numeric as.numeric(text) but all of these operations fail. How can I make this string-vector a vector (or matrix/list, whatever) again?

Upvotes: 1

Views: 23

Answers (1)

akrun
akrun

Reputation: 886938

We could use eval/parse

text1 <- eval(parse(text = text))
str(text1)
#num [1:8] 22.8 23.4 21.8 22.8 50.1 ...


Instead of saving it as a string, it may be better to use dput and save it in a .R file, then it can be reproduced easily

dput(head(iris))

Upvotes: 1

Related Questions