我需要替换字符向量的某些值:
x <- data.frame(Strings = c("one", "two","three","four","five","four","five","four","five","two","thre","two","three","two","three"), stringsAsFactors = FALSE)
> x
Strings
1 one
2 two
3 three
4 four
5 five
6 four
7 five
8 four
9 five
10 two
11 three
12 two
13 three
14 two
15 three
在 python 中,我会这样做:
x["Strings"].replace(["one", "two", "thre","three"], ["One","Two","Three","Three"], inplace=True)
但是在 r 函数中
replace()
不以同样的简单方式工作。 Stackoverflow 中的字符串替换有很多解决方案,但没有一个这么简单。这在 r 中可能吗?
最佳答案
如果您只想将每个单词的第一个字母大写,我们可以使用 sub
:
x$new <- sub('^([a-z])', '\\U\\1', x$Strings, perl = TRUE)
输出:
Strings new
1 one One
2 two Two
3 three Three
4 four Four
5 five Five
6 four Four
7 five Five
8 four Four
9 five Five
10 two Two
11 thre Thre
12 two Two
13 three Three
14 two Two
15 three Three
如果已经有新旧词替换列表,我们可以使用
str_replace_all
,它与发布的python示例OP具有(某种)相似的风格:library(stringr)
pattern <- c("one", "two", "thre", "three")
replacements <- c("One", "Two", "Three", "Three")
named_vec <- setNames(replacements, paste0("\\b", pattern, "\\b"))
x$new <- str_replace_all(x$Strings, named_vec)
或与
match
或 hashmap
:library(dplyr)
x$new <- coalesce(replacements[match(x$Strings, pattern)], x$new)
library(hashmap)
hash_lookup = hashmap(pattern, replacements)
x$new <- coalesce(hash_lookup[[x$Strings]], x$new)
输出:
Strings new
1 one One
2 two Two
3 three Three
4 four four
5 five five
6 four four
7 five five
8 four four
9 five five
10 two Two
11 thre Three
12 two Two
13 three Three
14 two Two
15 three Three
关于R 相当于 python 中的 string.replace(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54789927/