如何从r中的数据帧中的列表中提取数字信息?

时间:2014-11-15 14:58:21

标签: r dataframe

我在名为dfgModsPepFiltered_subset的数据框的第一列中有以下类型的条目:

A640-P641 = 456.123x

尝试使用以下R脚本从中提取数字信息:

dfgModsPepFiltered_subset$AA <- regmatches(dfgModsPepFiltered_subset$Peptide,
        gregexpr("[[:digit:]]+", dfgModsPepFiltered_subset$Peptide))

给我:

c("640", "641", "453", "123")

但是,我真正需要的是"640""641""456.123"每个新列。

我尝试了各种不公开的组合,但似乎无法使格式正确。

1 个答案:

答案 0 :(得分:3)

您可以修改regmatches

 as.data.frame(do.call(`rbind`,
         lapply(regmatches(dfgModsPepFiltered_subset$Peptide,
             gregexpr("[[:digit:].]+", dfgModsPepFiltered_subset$Peptide)), 
                                                        as.numeric))

  #   V1  V2      V3
  #1 640 641 456.123
  #2 620 625 285.400

或使用extract

中的tidyr
library(tidyr)
res <-  extract(dfgModsPepFiltered_subset, Peptide, c('Col1', 'Col2', 'Col3'),
               '[A-Z](\\d+)-[A-Z](\\d+) += +(\\d+\\.\\d+).+', convert=TRUE) 


res
#  Col1 Col2    Col3
#1  640  641 456.123
#2  620  625 285.400

或者您可以使用regex

extract(dfgModsPepFiltered_subset, Peptide, c('Col1', 'Col2', 'Col3'),
        '[^0-9]+([0-9]+)[^0-9]+([0-9]+)[^0-9]+([0-9.]+)[^0-9]+')

或者

library(splitstackshape)
res1 <-  cSplit(dfgModsPepFiltered_subset, 'Peptide', '[^0-9.]', fixed=FALSE)
res1[,names(res1)[!colSums(is.na(res1))], with=FALSE]
#   Peptide_2 Peptide_4 Peptide_7
#1:       640       641   456.123
#2:       620       625   285.400

或使用strsplit

 as.data.frame(t(sapply(strsplit(dfgModsPepFiltered_subset$Peptide,
                       '[^0-9.]'), function(x) na.omit(as.numeric(x)))))

 #   V1  V2      V3
 #1 640 641 456.123
 #2 620 625 285.400

数据

dfgModsPepFiltered_subset <- data.frame(Peptide= c('A640-P641 = 456.123x',
       'A620-B625 = 285.400x'), stringsAsFactors=FALSE)