user11497093
user11497093

Reputation:

Split string to data frame in R

I have data string str1 in the following format;

str1 <- "([0.1,0.2,0.3,......],[timestamp('2019-03-09'),timestamp('2019-03-09'),timestamp('2019-03-09'), .....],[0.1,0.2,0.3,......],[true,false,true,false,.....])"

I need to convert this string to a dataframe df, where values of each variable is a by substring from [ ]. Example as shown below,

df

 A              B                 C         D
0.1  timestamp('2019-03-09')     0.1       True
0.2  timestamp('2019-03-09')     0.2       False
0.3  timestamp('2019-03-09')     0.3       True
0.4  timestamp('2019-03-09')     0.4       False

Upvotes: 0

Views: 63

Answers (1)

s_baldur
s_baldur

Reputation: 33488

This seems to be Python code... maybe best to initialzie in Python and export as csv or similar?

Anywhere here is something a bit raw using R:

library(magrittr)
strsplit(str1, "],[", fixed = TRUE)[[1]] %>% 
  gsub("^\\(\\[|\\]\\)$", "", .) %>% 
  lapply(strsplit, ",") %>% 
  as.data.frame() %>% 
  setNames(LETTERS[1:4])

#     A                        B   C     D
# 1 0.1  timestamp('2019-03-09') 0.1  true
# 2 0.2  timestamp('2019-03-09') 0.2 false
# 3 0.3  timestamp('2019-03-09') 0.3  true
# 4 0.4  timestamp('2019-03-09') 0.4 false

Data

str1 <- "([0.1,0.2,0.3,0.4],[timestamp('2019-03-09'),timestamp('2019-03-09'),timestamp('2019-03-09'), timestamp('2019-03-09')],[0.1,0.2,0.3,0.4],[true,false,true,false])"

Upvotes: 2

Related Questions