使用 gsub 或类似函数将一个字符变量替换为另一个字符变量的一部分

Using gsub or similar function to replace one character variable with part of another character variable

我希望这是一个简单的问题。

我有两个变量,我想从另一个变量中取出一个变量的字符串,基本上是为了得到第二个变量中剩下的任何其他内容

variable1='test'
variable2='test2'
wantedresult='2'

newdf=as.data.frame(cbind(variable1,variable2,wantedresult))

如果 gsub 使用 2 列,我会使用它,但第一个参数必须是字符串而不是变量

gsub(newdf$variable2,'',newdf$variable1)

还有其他方法吗? 谢谢

如果有多行,则必须使用可以向量化操作的技术。这是一个使用 mapply.

的示例
# Create example data frame
variable1 <- c('test', 'bus')
variable2 <- c('test2', 'bus3')
wantedresult <- c('2', '3')

newdf <- data.frame(variable1, variable2, wantedresult, stringsAsFactors = FALSE)
newdf
#   variable1 variable2 wantedresult
# 1      test     test2            2
# 2       bus      bus3            3

# Apply the gsub function using mapply
mapply(gsub, pattern = newdf$variable1, replacement = "", x = newdf$variable2)
# test  bus 
# "2"  "3"

这里有一个选项data.table

# data
variable1 <- 'test'
variable2 <- 'test2'
newdf <- as.data.frame(cbind(variable1,variable2))
# solution
library(data.table)
setDT(newdf)[, wantedresult := gsub(variable1, '', variable2, fixed = TRUE)]
newdf # output
  variable1 variable2 wantedresult
1:      test     test2            2