1

I've been given an odd file out of 0365 that seems to be delimited by : and , with quotations. I want to get these into separate columns and values.

An example below:

CreationDate UserID  AuditData 
2020-05-04   User1   {"Id":"4ccd2","RecordType":20,"CreationTime":"2020-05-04T10:24:44"} 
2020-04-14   User2   {"Id":"4def5","RecordType":18,"CreationTime":"2020-04-14T10:24:44"} 
2020-03-29   User3   {"Id":"4zxc2","RecordType":07,"CreationTime":"2020-03-29T10:24:44"}

Goal: Break out the column AuditData into: 1) Id and value 2) RecordType and value 3) CreationTime and value

etc etc

I've been trying a couple things with separate() but have been unsuccessful so far. Thanks!

1 Answer 1

1

Here is a tidyverse solution using separate.

#Your data
df<-read.csv(text = 'CreationDate UserID AuditData
2020-05-04 User1 {"Id":"4ccd2","RecordType":20,"CreationTime":"2020-05-04T10:24:44"}
2020-04-14 User2 {"Id":"4def5","RecordType":18,"CreationTime":"2020-04-14T10:24:44"}
2020-03-29 User3 {"Id":"4zxc2","RecordType":07,"CreationTime":"2020-03-29T10:24:44"}',
         sep = " ")

library(tidyverse)
df %>%
   # remove keys using gsub
   mutate_at(vars(AuditData), function(x) gsub("\\{|\\}","",x)) %>%
   # separate using the colon or comma (however this separates also the time values)
   separate(col = AuditData, 
            # Define the new column names
            into = c("Id","Idvalue","RecordType","RecordTypevalue","CreationTime","temp","time1","time2"),
            # Use : or , as separators
            sep = "\\:|\\,") %>%
   # Use paste to reconstruct the time values
   mutate(CreationTimevalue = paste(temp,time1,time2, sep = ":")) %>%
   # Eliminate unused columns: temp, time1 and time2 
   select(-c(temp,time1,time2))

# CreationDate UserID Id Idvalue RecordType RecordTypevalue CreationTime   CreationTimevalue
# 1   2020-05-04  User1 Id   4ccd2 RecordType              20 CreationTime 2020-05-04T10:24:44
# 2   2020-04-14  User2 Id   4def5 RecordType              18 CreationTime 2020-04-14T10:24:44
# 3   2020-03-29  User3 Id   4zxc2 RecordType              07 CreationTime 2020-03-29T10:24:44
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.