簡體   English   中英

通過 lapply 和正則表達式批量創建列到 R 的 data.table 中的列

[英]batch create columns by lapply and regex to a column in data.table of R

我想在一些字符串之后獲取值,演示如下

dt <- data.table(col.1 = c("a1, b2, c3, d4"))
x <- c("a", "b", "c")

dt[, (x) := lapply(FUN = str_match(string = .SD, 
                                   pattern = paste0("(?<=", x, ")([\\d])"))[, 2], 
                   X = x),
   .SDcols = "col.1"]

理想的結果看起來像這樣

desirable <- data.table(col.1 = c("a1, b2, c3, d4"),
                        a = c("1"),
                        b = c("2"),
                        c = c("3"))

我收到如下錯誤信息:

* match.fun(FUN) 錯誤:

c("'str_match(string = .SD, pattern = paste0(\"(?<=\", x, \")([\\\\d])\"))[, ' is not a function, character or symbol", "'    2]' is not a function, character or symbol")*

但我不知道如何解決這個問題。 誰能給我一些hins?

遍歷模式並使用str_match提取值

library(data.table)
library(stringr)
dt[, (x) := lapply(paste0("(?<=", x, ")(\\d+)"),
     \(x) str_match(col.1, x)[, 2])]
            col.1 a b c
1: a1, b2, c3, d4 1 2 3

或者用strcapture

pat <- paste0(sprintf("%s(\\d+)", x), collapse = ".*")
cbind(dt, dt[, strcapture(pat, col.1, setNames(rep(list(integer()), 3), x))])
            col.1 a b c
1: a1, b2, c3, d4 1 2 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM