分析字符串中的每个数字,并存储在 R 中的新列中



下面是我在 R 中的数据帧中的示例行,我正在寻找一种方法来拆分其自己列中的 12 个数字中的每一个。

Pos. Part.: 16       , 18       , 28       , 37       , 64       , 67     Neg. Part.: 11       , 28       , 34       , 41       , 55       , 72

实现此目的的最佳字符串操作函数是什么?谢谢!

@Chris的答案整齐地提取了数字,但我怀疑你的问题是它合并了 Pos 和 Neg,然后你不能将它们分开。如果你总是同时得到 Pos 和 Neg,你可以使用一个正则表达式来抓取这两个组。但是,如果您只能获得一个或另一个,那么您将不知道通过单个匹配项找到了哪个。

因此,最可靠的方法是分别搜索 Pos 和 Neg。下面的代码使用了一个称为后视的regexpr技巧。它匹配前面有另一种模式的文本,但匹配中不包含另一种模式。我们只是在数字之后(空格逗号和 0-9 的混合(。所以给定:

ch <- 'Pos. Part.: 16       , 18       , 28       , 37       , 64       , 67     Neg. Part.: 11       , 28       , 34       , 41       , 55       , 72'

我们可以用它来获得16 , 18 , 28 , 37 , 64 , 6711 , 28 , 34 , 41 , 55 , 72,然后可以得到数字。

pos <- regexpr('(?<=Pos. Part.:)[ ,0-9]+', ch, perl=TRUE)
neg <- regexpr('(?<=Neg. Part.:)[ ,0-9]+', ch, perl=TRUE)

现在我们可以提取这些匹配并回到数字。

pos <- regmatches(pos, ch)
neg <- regmatches(neg, ch)
pos <- strsplit

我们现在可以使用@Chris的模式来提取数字,但也可以只使用strsplit.以pos为例:

pos <- strsplit(pos, ',')[[1]]
# That leaves spaces all over the place, so:
pos <- trimws(pos)
[1] "16" "18" "28" "37" "64" "67"

如果你只追求数字,这应该可以工作:

#data:
hockey <- c("Pos. Part.: 16       , 18       , 28       , 37       , 64       , 67     Neg. Part.: 11")
# define pattern to be matched:
pattern <- "\d{2}"
# define function to extract raw matches:
extract <- function(x) unlist(regmatches(x, gregexpr(pattern, x, perl = T)))
# extract raw matches:
extract(hockey)
extract
[1] "16" "18" "28" "37" "64" "67" "11"

如果数字在它们包含的数字字符数方面可以变化,请按以下方式调整pattern

pattern <- "\d{1,}" # matches numbers with at least one numeric character

最新更新