在R中查找字符串匹配

在R中查找字符串匹配,r,regex,gsub,R,Regex,Gsub,我的data.frame有两列和数千行随机字符串,如下所示: Column1 Column2 "this is done in 1 hour" "in 1 hour" 我想得到一个新的data.frame列,如下所示: Column3 "this is done" 因此,基本上根据Column2匹配字符串,并得到Column1的剩余部分。如何处理这个问题 编辑: 这无法解决问题,因为字符串的长度不同,因此我无法执行以下操作: substr

我的data.frame有两列和数千行随机字符串,如下所示:

Column1                      Column2
"this is done in 1 hour"     "in 1 hour" 
我想得到一个新的data.frame列,如下所示:

Column3
"this is done" 
因此,基本上根据Column2匹配字符串,并得到Column1的剩余部分。如何处理这个问题

编辑:

这无法解决问题,因为字符串的长度不同,因此我无法执行以下操作:

substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}

substrRight(x, 3)

substrRight下面是一个示例,说明如何执行此操作:

# example data frame
testdata <- data.frame(colA=c("this is","a test"),colB=c("is","a"),stringsAsFactors=FALSE)

# adding the new column
newcol <- sapply(seq_len(nrow(testdata)),function(x) gsub(testdata[x,"colB"],"",testdata[x,"colA"],fixed=TRUE))
new.testdata <- transform(testdata,colC=newcol)

# result
new.testdata
#      colA | colB  | colC
# --------------------------
# 1 this is |   is  | th 
# 2  a test |    a  |   test

您可以使用正则表达式执行此操作:

data <- data.frame(Column1 = "this is done in 1 hour", Column2 = "in 1 hour")
data$Column3 <- gsub(data$Column2, '', data$Column1) # Replace fist parameter by second in third.

colC应该是
this
。总之,非常接近。谢谢。我也在想同样的方法,但我不知道为什么,我认为它更复杂。谢谢。如果
data.frame
有多行,则这不会按预期方式工作。
data <- data.frame(Column1 = "this is done in 1 hour", Column2 = "in 1 hour")
data$Column3 <- gsub(data$Column2, '', data$Column1) # Replace fist parameter by second in third.
data <- data.frame(Column1 = c("this is done in 1 hour", "this is a test"), Column2 = c("in 1 hour", "a test"))
data$Column3 <- mapply(gsub, data$Column2, '', data$Column1)