我如何改进这段代码?
data$tidy <- sapply(data$tidy,function(x) {x <- gsub("one","1",x)})
data$tidy <- sapply(data$tidy,function(x) {x <- gsub("two","2",x)})
data$tidy <- sapply(data$tidy,function(x) {x <- gsub(“first”,"1",x)})
data$tidy <- sapply(data$tidyfunction(x) {x <- gsub("second","2",x)})一般的想法是:如果我找到一个“1”或“第一个”,我就把它替换成1。
这段代码正在工作,但我完全相信这可能会更有效率。
发布于 2020-05-02 12:09:30
因为我们不知道你的data$tidy是什么样子的,所以我将编造一些假数据。
mydata <- data.frame(tidy = c("my one is not two", "two going into first or second", "twenty five or six to four"), stringsAsFactors = FALSE)
mydata
# tidy
# 1 my one is not two
# 2 two going into first or second
# 3 twenty five or six to four
mydata$tidy <- gsub("(one|first)", "1", gsub("(two|second)", "2", mydata$tidy))
mydata
# tidy
# 1 my 1 is not 2
# 2 2 going into 1 or 2
# 3 twenty five or six to four由于您正在进行子字符串替换,因此merge和fuzzyjoin::都不会执行您需要的操作。虽然我们可以减少/组合一些模式,但我不知道有什么简单的方法可以绕过这样的单个规范。
发布于 2020-05-02 12:19:03
gsub是矢量化的,所以这里并不真正需要sapply。
您可以在这里使用str_replace_all,将命名向量作为replacement和pattern进行传递。
使用@r2evans数据。
a <- c('1', '2')
names(a) <- c('one|first', 'two|second')
stringr::str_replace_all(mydata$tidy, a)
#[1] "my 1 is not 2" "2 going into 1 or 2" "twenty five or six to four"https://stackoverflow.com/questions/61554285
复制相似问题