我正在寻找更快的方法来实现以下目标,我需要将包含字符串的data.table对象的列拆分为单独的列。字符串的格式为“name1 = value1; name2 = value2;”。字符串可以拆分为可变数量的列,在这种情况下,这些值需要用NA填充。例如,我有这个:
library(data.table)
dt <- data.table("foo"=c("name=john;id=1234;last=smith", "name=greg;id=5678", "last=picard", "last=jones;number=1234567890"))
我想要这个:
name id last number
john 1234 smith NA
greg 5678 NA NA
NA NA picard NA
NA NA jones 1234567890
这会有效,但考虑到要解析的数据量很慢,我想知道是否有更好的方法:
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)
答案 0 :(得分:3)
我们可以尝试:
# split into different fields for each row
res <- lapply(strsplit(dt$foo, ';'), function(x){
# split the the fields into two vectors of field names and field values
res <- tstrsplit(x, '=')
# make a list of field values with the field names as names of the list
setNames(as.list(res[[2]]), res[[1]])
})
rbindlist(res, fill = T)
# name id last number
# 1: john 1234 smith NA
# 2: greg 5678 NA NA
# 3: NA NA picard NA
# 4: NA NA jones 1234567890
dplyr::bind_rows(res)
# # A tibble: 4 × 4
# name id last number
# <chr> <chr> <chr> <chr>
# 1 john 1234 smith <NA>
# 2 greg 5678 <NA> <NA>
# 3 <NA> <NA> picard <NA>
# 4 <NA> <NA> jones 1234567890
根据David Arenburg的评论,我们可以通过向fixed = TRUE
添加strsplit
来提高速度。我对这些数据进行了简短的基准测试,添加fixed = TRUE
会将速度提高一倍左右。
library(microbenchmark)
dt <- dt[sample.int(nrow(dt), 100, replace = T)]
microbenchmark(
noFix = {
res <- lapply(strsplit(dt$foo, ';'), function(x){
res <- tstrsplit(x, '=')
setNames(as.list(res[[2]]), res[[1]])
})
},
Fixed = {
res <- lapply(strsplit(dt$foo, ';', fixed = TRUE), function(x){
res <- tstrsplit(x, '=', fixed = TRUE)
setNames(as.list(res[[2]]), res[[1]])
})
},
times = 1000
)
# Unit: milliseconds
# expr min lq mean median uq max neval
# noFix 1.921947 1.999386 2.212511 2.064997 2.218706 11.290072 1000
# Fixed 1.026753 1.088712 1.226519 1.131899 1.219558 4.490796 1000