使用R将包含罗马数字的字符串转换为数字。

huangapple go评论56阅读模式
英文:

Convert string containing roman numerals to numeric using R

问题

当前输出:

3 2 3 3 2 5

期望输出:

2 1 2 2 1 4
英文:

I want to convert "stage i", "stage ii", etc to numeric "1" and "2".

pheno_df$pathologic_stage <- gsub("stage ","",pheno_df$pathologic_stage)
as.numeric(factor(pheno_df$pathologic_stage))

Current output:

3 2 3 3 2 5

Desired output:

2 1 2 2 1 4

Data sample:

> dput(pheno_df$pathologic_stage)
c("stage ii", "stage i", "stage ii", "stage ii", "stage i", "stage iv",

答案1

得分: 3

提取数字部分,然后转换为罗马数字,再转换回数字:

v <- c("stage ii", "stage i", "stage ii", "stage ii", "stage i", "stage iv")
as.numeric(as.roman(gsub("stage ", "", v)))
#[1] 2 1 2 2 1 4
英文:

Extract the numeral part, then convert to roman and back to numeric:

v &lt;- c(&quot;stage ii&quot;, &quot;stage i&quot;, &quot;stage ii&quot;, &quot;stage ii&quot;, &quot;stage i&quot;, &quot;stage iv&quot;)
as.numeric(as.roman(gsub(&quot;stage &quot;, &quot;&quot;, v)))
#[1] 2 1 2 2 1 4

huangapple
  • 本文由 发表于 2023年2月16日 19:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定