从 R 中的字符串中删除数字

vel*_*ock 5 r gsub

我正在尝试使用函数从字符串中删除除 67 之外的所有数字gsub

例如:

txt <- "A function 147832 for 67cleaning 67 data 6 7"
Run Code Online (Sandbox Code Playgroud)

期望输出:

txt <- "A function for 67cleaning 67 data"
Run Code Online (Sandbox Code Playgroud)

我试过了txt = gsub("[[:digit:]]", "", txt),但它会删除所有数字。

Vee*_*kar 2

你可以这样做

x = unlist(strsplit(txt, split = '\\s+')) # split your string
paste0(x[Reduce(`|`, lapply(c('[A-Za-z]', '67'), grepl, x))], collapse = ' ') # use the list of regular expression to match the required pattern and put them all together

#[1] "A function for 67cleaning 67 data"
Run Code Online (Sandbox Code Playgroud)