r - 使用 gsub 或类似函数将一个字符变量替换为另一个字符变量的一部分
问题描述
我希望这是一个简单的问题。
我有两个变量,我想从另一个变量中取出一个变量的字符串,基本上是为了得到第二个变量中剩下的任何东西
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"
推荐阅读
- kubernetes - 在哪里执行 kube-proxy 命令?
- java - Sort an array of instances of a custom class based on a field
- ios - 无法在真实 iPhone 上使用 @ObservedObject
- api-design - 为什么 facebook 的转换像素会加载多个 JavaScript 文件?
- r - Foxall 的 G 函数在 R spatstat 中具有多边形
- selenium - Selenium 错误 - org.openqa.selenium.SessionNotCreatedException 会话创建异常
- mysql - 如何将行值放入新列以提高可读性?
- python - OpenCV 检测人脸、裁剪轮廓、使用 grabCut 以编程方式标记和移除背景
- javascript - Javascript | 使用对象循环遍历对象数组
- android - 服务每分钟发送一次位置,即使应用程序在后台或系统重新启动