删除R中的部分字符串

数据挖掘 r 数据集 生物信息学
2021-09-30 23:43:41

我在 R 中有一个表。它只有两列和多行。每个元素都是一个包含一些字符和一些数字的字符串。我需要元素的数字部分。我怎样才能有数字部分?例如:

    INTERACTOR_A INTERACTOR_B
1          ce7380       ce6058
2          ce7380      ce13812
3          ce7382       ce7382
4          ce7382       ce5255
5          ce7382       ce1103
6          ce7388        ce523
7          ce7388       ce8534

谢谢

4个回答

你可以使用gsub函数

> c <-  "ce7382"
> gsub("[a-zA-Z ]", "", c)
[1] "7382"

随意将您需要删除的其他字符添加到正则表达式和/或将结果转换为数字as.numeric

ce7380如果不需要的字符在示例中是恒定的,例如不需要的字符,ce则可以尝试以下操作:

library(stringr)
df <- df %>%
      mutate_at("INTERACTOR_A", str_replace, "ce", "")

这指示 R 执行列中的变异函数,INTERACTOR_A并将常数替换为ce空。

如果不需要的字符逐行变化,那么此处提供的其他正则表达式方法可能更合适。

与前面的一个类似,您还可以应用从(即包括)第一个数字数字开始提取所有内容的逻辑:

interactor <- c("ce7380", "ce7382", "ce7388")
x <- gregexpr("[0-9]+", interactor)
x <- unlist(regmatches(interactor, x))
x
## [1] "7380" "7382" "7388"

我会这样做:

library(roperators)

# either 
this_text <- c('ce7380', 'ce5932', 'ce1234')

# make a new text vector:
new_text <- this_text %-% '[a-z]'

# or make an integer vector:
new_number <- int(this_text %-% '[a-z]')

# OR change this_text in-place
this_text <- c('ce7380', 'ce5932', 'ce1234')

this_text %-=% '[a-z]'