首页 > 解决方案 > 使用 gsub 或类似函数将一个字符变量替换为另一个字符变量的一部分

问题描述

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

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

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

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

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

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

还有另一种方法可以做到这一点吗?谢谢

标签: rstringgsub

解决方案


如果您有多行,则必须使用可以矢量化操作的技术。这是一个使用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"

推荐阅读