We could group by rows (rowwise
), then convert the 'mycol' element with fromJSON
to a list
of matrix
es, unlist
to vector
, convert the vector to a data.frame with 4 columns using as.data.frame.list
, wrap it in a list
, then we ungroup
and unnest
the list
column with unnest_wider
(from tidyr
) and finally, convert the column types based on its value with type.convert
library(dplyr)
library(jsonlite)
library(tidyr)
d %>%
rowwise %>%
mutate(newcol = list(setNames(as.data.frame.list(unlist(fromJSON(mycol,
simplifyVector = FALSE)[[2]] )), paste0("X", 1:4)))) %>%
ungroup %>%
unnest_wider(c(newcol)) %>%
type.convert(as.is = TRUE)
-output
# A tibble: 3 x 5
# mycol X1 X2 X3 X4
# <chr> <dbl> <int> <dbl> <int>
#1 "[[[\"0.10\", \"35\"], [\"0.2\", \"36\"]], [[\"5.1\", \"2\"], [\"90.2\", \"2\"]]]" 5.1 2 90.2 2
#2 "[[[\"0.10\", \"35\"], [\"0.2\", \"36\"]], [[\"5.1\", \"2\"], [\"90.2\", \"2\"]]]" 5.1 2 90.2 2
#3 "[[[\"0.10\", \"35\"], [\"0.2\", \"36\"]], [[\"5.1\", \"2\"], [\"90.2\", \"2\"]]]" 5.1 2 90.2 2
data
d <- structure(list(mycol = c("[[[\"0.10\", \"35\"], [\"0.2\", \"36\"]], [[\"5.1\", \"2\"], [\"90.2\", \"2\"]]]",
"[[[\"0.10\", \"35\"], [\"0.2\", \"36\"]], [[\"5.1\", \"2\"], [\"90.2\", \"2\"]]]",
"[[[\"0.10\", \"35\"], [\"0.2\", \"36\"]], [[\"5.1\", \"2\"], [\"90.2\", \"2\"]]]"
)), class = "data.frame", row.names = c(NA, -3L))