【问题标题】:Using gsub or similar function to replace one character variable with part of another character variable使用 gsub 或类似函数将一个字符变量替换为另一个字符变量的一部分
【发布时间】:2018-09-19 13:28:45
【问题描述】:

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

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

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

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

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

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

还有其他方法可以做到这一点吗? 谢谢

【问题讨论】:

  • newdf <- data.frame(variable1='test', variable2='test2'); newdf$wanted <- with(newdf, gsub(variable1, '', variable2, fixed = TRUE)); newdf

标签: r string gsub


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是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
    

    【讨论】:

      猜你喜欢
      • 2019-11-21
      • 1970-01-01
      • 2014-03-13
      • 2019-11-08
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 2017-01-04
      • 2018-09-22
      相关资源
      最近更新 更多