首页 > 解决方案 > 将 data.table 转换组合在一行中

问题描述

我写了一个 data.table 数据转换代码:

table_patterns <- table[, pattern := stringr::str_extract(LOG_MSG, "\\S+\\s+\\S+\\s+\\S+")]
table_patterns <- table_patterns[, pattern := coalesce(stringr::str_extract(pattern, "^create new|regulate values"),pattern)]
table_patterns <- table_patterns[, system_type := case_when(class%in% c("class1", "class2") ~ "creation_class",class%in% c("class3","class4") ~ "uploading class")]
table_patterns <- table_patterns[, source := case_when(message%in% c("adapting new values within system|data wrangling and transformation in system") | class %in% c("class5", "class6") | pattern %in% c("user1 has uploaded new text") ~ "text_uploading",class %in% c("class7") ~ "alt_class",TRUE ~ "self_search"), by = .(class, pattern, system_type,source,message_type)][,
    

如您所见,我创建了 table_patterns,然后对其进行了三次转换。我怎么能在一个过程中做到这一点。不修改三遍?不需要数据示例,它是关于代码语法的,所以不需要数据示例。

标签: rdata.table

解决方案


随着data.table:=修改到位。因此,无需将输出 ( <-) 分配给另一个对象。多个参数的链接可以完成为

library(data.table)
table[, pattern := stringr::str_extract(LOG_MSG, "\\S+\\s+\\S+\\s+\\S+")
      ][, pattern := coalesce(stringr::str_extract(pattern, 
         "^create new|regulate values"),pattern), by = .(class, pattern)
      ][, system_type := case_when(class%in% c("class1", "class2") ~
           "creation_class",
      class%in% c("class3","class4") ~ "uploading class"), by = .(class, pattern)
      ][, source := case_when(message %in% 
           c("adapting new values within system|data wrangling and transformation in system") | 
                class %in% c("class5", "class6") | 
                pattern %in% c("user1 has uploaded new text") ~
                   "text_uploading", 
                class %in% c("class7") ~ "alt_class",
         TRUE ~ "self_search"),
         by = .(class, pattern, system_type,source,message_type)][]
    
    

推荐阅读