gpt4 book ai didi

r - 从字符串中提取数字并复制它们的关联值

转载 作者:行者123 更新时间:2023-12-02 06:31:49 25 4
gpt4 key购买 nike

我目前有这段代码:

args <- commandArgs(TRUE)
args[1] <- "H2SO4"

components <- gsub('([[:upper:]])', ' \\1', args[1])
components <- c(unlist(strsplit(components, " ")))[-1]

输入 H2SO4 结果向量为:

[1] "H2" "S"  "O4"

现在我如何将数字与字母分开,并使该类型字母的数量与提取的数字相符。所以输出看起来像:

[1] "H" "H" "S" "O" "O" "O" "O"

最佳答案

我们可以用gsubfn复制字符串的数字部分的字符,然后用str_extract_all提取字符。

library(gsubfn)
library(stringr)
str_extract_all(gsubfn('(\\D)(\\d+)', ~rep(x,y), str1),'[A-Z]')[[1]]
#[1] "H" "H" "S" "O" "O" "O" "O"

str_extract_all(gsubfn('(\\D)(\\d+)', ~rep(x,y), str2),'[A-Z]')[[1]]
#[1] "C" "C" "C" "C" "H" "H" "H" "H" "H" "H" "H" "H" "H" "H" "O"

str_extract_all(gsubfn('([A-Z][a-z]*)(\\d+)', ~rep(x,y),
str3), '[A-Z][a-z]*')[[1]]
#[1] "Fe" "Fe" "Fe"

str_extract_all(gsubfn('([A-Z][a-z]*)(\\d+)', ~rep(x,y),
str4), '[A-Z][a-z]*')[[1]]
#[1] "Fe" "Fe" "O" "O" "O"

数据

str1 <- "H2SO4"
str2 <- "C4H10O"
str3 <- 'Fe3'
str4 <- 'Fe2O3'

关于r - 从字符串中提取数字并复制它们的关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com