data.table - gsub(搜索文本并替换为另一列的值)

data.table - gsub (search text and replace with value of another column)

我想搜索和替换另一列中的文本。是否可以利用 apply 系列的功能?

我正在寻找一个最好只包含 data.table 和基本 R 的解决方案。(不希望使用其他 stringr 等包)

library("data.table")
x <- mtcars
setDT(x)
x[,x1 := lapply(gear, gsub("1",gear,qsec))]

我们可以使用 Mapgsub

x[, x1 := unlist(Map(function(x, y) gsub("1", x,y), gear, qsec))]

-输出

> x$x1
 [1] "46.46" "47.02" "48.64" "39.44" "37.02" "20.22" "35.84" "20"    "22.9"  "48.3"  "48.9"  "37.4"  "37.6"  "38"    "37.98" "37.82" "37.42"
[18] "49.47" "48.52" "49.9"  "20.03" "36.87" "37.3"  "35.43" "37.05" "48.9"  "56.7"  "56.9"  "54.5"  "55.5"  "54.6"  "48.6" 

或使用str_replace

library(stringr)
 x[, x1 := str_replace_all(qsec, '1', as.character(gear))]