Jimmy TwoCents
Jimmy TwoCents

Reputation: 165

Text mining R seperate text into columns

I am doing a project in r and am analyzing text. I have strings of the form

 "id": 8784, "name": "Daniel", "age":"65", "gender":"M"  

and things of this sort. My question is how I can get the data so that each variable can become its own column, that is a name column, with the first entry being Daniel.

Upvotes: 0

Views: 83

Answers (1)

akrun
akrun

Reputation: 887391

The easiest would be to use the JSON route

library(jsonlite)
library(tidyverse)
sprintf("{%s}", str1) %>%
   fromJSON %>% 
   as.data.frame
#    id   name age gender
#1 8784 Daniel  65      M

If there are multiple strings, we can use

sprintf("{%s}", str1) %>% 
            map_df(fromJSON)

Update

Based on the OP's comments, if it also have [{..}]

str1 <- '[{"id": 8784, "name": "Daniel", "age":"65", "gender":"M"}]'
fromJSON(str1)
#    id   name age gender
#1 8784 Daniel  65      M

For multiple elements,

str1 <- c(str1, str1)
str1 %>% 
     map_df(fromJSON)
#    id   name age gender
#1 8784 Daniel  65      M
#2 8784 Daniel  65      M

data

str1 <- '"id": 8784, "name": "Daniel", "age":"65", "gender":"M"'

Upvotes: 2

Related Questions