基础 R
以下是一些基本的 R 解决方案:
1) 如果您只需要 FPrate 字段(这就是问题似乎要求的全部),那么这个 sub 就可以了。不需要任何软件包。
as.numeric(sub(".*FPrate:(\\S+) .*", "\\1", x))
## [1] 0.000 0.006 0.018 0.026 0.154 1.000
2) 如果你想解析出所有的 name:value 字段,那么,再一次,只使用 base R 用换行符替换前导非空格,然后替换每次出现的空格字符空格也有换行符。它现在是 dcf 格式,所以使用 read.dcf 读取它,给出字符矩阵m。这可能已经足够好了,但是如果您想要一个数据框,其中每一列都进行了适当的类型转换,那么将其转换为数据框d 并应用type.convert。此解决方案非常通用,因为它不会对 FPrate 和 OMEGA 进行硬编码。
s <- gsub(" . ", "\n", sub("\\S+", "\n", x))
m <- read.dcf(textConnection(s))
d <- as.data.frame(m, stringsAsFactors = FALSE)
d[] <- lapply(d, type.convert)
给予:
> m
FPrate OMEGA
[1,] "0.000" "D-904"
[2,] "0.006" "S-349"
[3,] "0.018" "S-337"
[4,] "0.026" "S-552"
[5,] "0.154" "S-549"
[6,] "1.000" "S-551"
> d
FPrate OMEGA
1 0.000 D-904
2 0.006 S-349
3 0.018 S-337
4 0.026 S-552
5 0.154 S-549
6 1.000 S-551
3) 这个使用strcapture,生成一个数据框,根据proto进行类型转换:
proto <- data.frame(FPrate = numeric(0), OMEGA = character(0))
strcapture(".*FPrate:(\\S+) . OMEGA:(\\S+)", x, proto)
给予:
FPrate OMEGA
1 0.000 D-904
2 0.006 S-349
3 0.018 S-337
4 0.026 S-552
5 0.154 S-549
6 1.000 S-551
4) 在这一节中,我们用空格替换冒号,读入 read.table 剩下的内容,提取我们想要的列,然后设置列名。没有使用正则表达式。
d <- read.table(text = chartr(":", " ", x), as.is = TRUE)[c(4, 7)]
names(d) <- c("FPrate", "OMEGA")
给出这个数据框:
FPrate OMEGA
1 0.000 D-904
2 0.006 S-349
3 0.018 S-337
4 0.026 S-552
5 0.154 S-549
6 1.000 S-551
gsubfn
5) 此解决方案使用 gsubfn 包。
library(gsubfn)
pat <- ".*FPrate:(\\S+).*OMEGA:(\\S+)"
nms <- c("FPrate", "OMEGA")
read.pattern(text = x, pattern = pat, as.is = TRUE, col.names = nms)
给予:
FPrate OMEGA
1 0.000 D-904
2 0.006 S-349
3 0.018 S-337
4 0.026 S-552
5 0.154 S-549
6 1.000 S-551