I am looking for a faster way to to the following, I need to split a column of a data.table object containing strings into separate columns. The strings are of the format "name1=value1;name2=value2;". The strings can be split into a variable number of columns in which case those values will need to be filled with NA. For example I have this:
library(data.table)
dt <- data.table("foo"=c("name=john;id=1234;last=smith", "name=greg;id=5678", "last=picard", "last=jones;number=1234567890"))
I would want this:
name id last number
john 1234 smith NA
greg 5678 NA NA
NA NA picard NA
NA NA jones 1234567890
This will work but it is slow given the amount of data to parse and I'm wondering if there is a better way:
x <- strsplit(as.character(dt$foo), ";|=")
a <- function(x){
name <- x[seq(1, length(x), 2)]
value <- x[seq(2, length(x), 2)]
tmp <- transpose(as.data.table(value))
names(tmp) <- name
return(tmp)
}
x <- lapply(x, a)
x <- rbindlist(x, fill=TRUE)