Ed_WFerreira
Ed_WFerreira

Reputation: 23

R data frame from contents of a character vector

I am working with a long character vector where each row is supposed to contain a small data frame. I created a function to clean the data and produce a string which would be ready to input to the data.frame() function. The output is as follows:

[1] "`demo/members/education_member` = c('High_school', 'High_school'), `demo/members/status` = c('Other', 'Other'), `demo/members/name` = c('Hans Solo', 'Luke Skywalker')"

I wanted to pass this output to data.frame() to obtain the following data frame (resulting from copying and pasting the unquoted output above and passing it to the data.frame function):

  demo.members.education_member demo.members.status demo.members.name
1                   High_school               Other         Hans Solo
2                   High_school               Other    Luke Skywalker

Question: What would be the best way to convert the contents of a character output into a R data frame?

Upvotes: 0

Views: 52

Answers (2)

Elin
Elin

Reputation: 6755

This is a way you can do it, if it is possible to add the data.frame() function to your string. If not let me know and I'll delete. This is a bit quick and dirty and uses rlang but you can make it better by not using base eval and instead figuring out the rlang quasiquotation stuff.

x <- "data.frame(
  'demomemberseducationmember' = c('High_school','High_school'), 
  'demomembersstatus' = c('Other', 'Other'), 
  'demmembersname' = c('Hans Solo', 'Luke Skywalker'))"
eval(rlang::parse_expr(x))

Upvotes: 0

Shree
Shree

Reputation: 11140

Here's a way but reiterating my comment - There is likely to be a better way to transform your raw data into a cleaned up dataframe.

x <- "`demo/members/education_member` = c('High_school', 'High_school'), `demo/members/status` = c('Other', 'Other'), `demo/members/name` = c('Hans Solo', 'Luke Skywalker')"

y <- paste0("data.frame(", x, ")")

eval(parse(text = y))

demo.members.education_member demo.members.status demo.members.name
1                   High_school               Other         Hans Solo
2                   High_school               Other    Luke Skywalker

Upvotes: 1

Related Questions