我有化学总式,例如 C6H12ON2PS
我希望他们这样订购:
| 求和公式 | C | H | 氧 | 氮 | 磷 | S |
|---|---|---|---|---|---|---|
| C6H12ON2PS | 6 | 12 | 1 | 2 | 1 | 1 |
| C6H12NP | 6 | 12 | 0 | 1 | 1 | 0 |
我的主要错误是,如果一个字母/元素不存在,并且当一个元素没有数字时,这意味着我需要在该列中添加 1 。
我不太擅长 R,因为我刚刚开始,我使用另一个人使用这些格式的脚本,但我只有文本。
我试过
str_split(strsplit(as.character(Form), '(?<=.)(?=[A-Z])', perl=TRUE))
Run Code Online (Sandbox Code Playgroud)
但是当一封信丢失时这不起作用
使用CHNOSZ::makeup:
CHNOSZ::makeup("C6H12ON2PS")
# C H O N P S
# 6 12 1 2 1 1
Run Code Online (Sandbox Code Playgroud)
我们可以使用data.table将化合物的特征向量转换为表格格式:
library(CHNOSZ)
library(data.table)
compounds <- c("C6H12ON2PS", "C6H12NP")
formulas <- makeup(compounds, count.zero = TRUE)
formulas <- data.table(compound = compounds)[
,names(formulas[[1]]) := transpose(formulas)
]
print(formulas)
#> compound C H N O P S
#> 1: C6H12ON2PS 6 12 2 1 1 1
#> 2: C6H12NP 6 12 1 0 1 0
Run Code Online (Sandbox Code Playgroud)