Reputation: 165
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
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)
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
str1 <- '"id": 8784, "name": "Daniel", "age":"65", "gender":"M"'
Upvotes: 2